Brian Fleishman Brian Fleishman - 2 months ago 6
Ajax Question

Iterating over JSON Data on AJAX Success Using JQuery

I have an AJAX call that return JSON data from a query:

<script>
function retrieveTrips(){
// Get a history of trips

$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);
console.log(response);
}
});
}
</script>


I would like to iterate over the returned JSON data on the success function and output it to an HTML table using JQUERY. The closest I can come to this is just outputting all the data to a div in my table. Can anyone give me a hand on how that JQUERY code would look?

Here is my JSON response:

{
"COLUMNS": ["ID", "VEHICLE_ID", "TICKET_ID", "_DATE", "START_ODOMETER", "END_ODOMETER", "ORIGIN", "DESTINATION", "TOTAL_MILEAGE", "EXPENSES", "DESCRIPTION"],
"DATA": [
[1650, "6", "30996", "September, 29 2016 00:00:00 -0400", "11782", "11822", "Jaydien", "Mazza", "40", "0.00", ""]
]
}


MY EDITS:



<script>
function retrieveTrips(){
// Get a history of trips

$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);

for (i = 0; i < response.DATA.length; i++) {
var row = response.DATA[i];
console.log(row);
}

}
});
}
</script>

Answer

Try this in your success call, place this instead of your console.log();

response = JSON.parse(response);

for (i = 0; i < response.DATA.length; i++) { 
    var row = response.DATA[i];
    console.log(row);
}

Also you have a ## which should be just 1 # or else it wont return to the propper element

The return json is a JSON returned with two properties both containing an Array the first property tell you what the columns mean the second one contains the actual data, to approach only the data you call response.DATA, DATA is the property name in the json object