This post shows the examples of parsing a JSON from a jQuery ajax call.
1. SimpleJSON
[
{
customer_id:"1",
customer_name: "Jim"
},
{
customer_id:"2",
customer_name: "Joe"
}
]
Following is the AJAX call to parse the simple JSON data from the service
$('#ajax1').click(function(){
$.ajax({
url: "http://www.mocky.io/v2/54be41e83792d53a0ba6d5f3",
dataType: "jsonp",
success: function(result, status){
$('#result1').append("Status of the rest service is "+ status);
$.each(result,function(index){
$('#result1').append("
"+result[index].customer_id+" -- "+result[index].customer_name);
});
}
});
});
Note : I have used dataType as jsonp since , the the service I am fetching data from is on another domain.
2. Complex JSON
Host Laravel Application on DigitalOcean
Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
{
"employee": [{
"firstName": "John",
"LastName": "LaPhon",
"phoneNumber": ["7046996952", "7897786677"]
},
{
"firstName": "User",
"LastName": "Test",
"phoneNumber": ["23246952", "932423219"]
}
]
}
Following is the ajax call to parse above JSON request
$('#ajax2').click(function(){
$.ajax({
url : 'http://www.mocky.io/v2/54bf7334a84e11cc06149872',
dataType : "jsonp",
success : function(result, status){
var employees = result.employee;
$.each(employees,function(index){
$('#result2').append("
"+employees[index].firstName+" -- "+employees[index].LastName);
var phoneNumbers = employees[index].phoneNumber;
$.each(phoneNumbers, function(j){
$('#result2').append(" "+phoneNumbers[j]+" ");
});
});
}
});
});