Iterating over JSON Data on AJAX Success Using JQuery - javascript

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>

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

Related

javascript to filter json and return another value

I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]

Convert data from received JSON format to JVectorMap format

I am developing dashboard of a MIS in MVC 5, and in that dashboard I want to use JVectorMap to load the registered countries. So following is my controller action that returns the JSON
public JsonResult registeredCountries()
{
var ret = db.View_RegisteredCountries.Select(x => new { Key = x.CountryCode, Value = x.TotalCompanies }).ToDictionary(x => x.Key, x => x.Value).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
and following is my JS code to get the JSON
var data = {};
$.ajax({
url: 'registeredCountries',
type: 'GET',
traditional: true,
async: false,
cache: false,
//async: false,
dataType: 'json'
}).done(function(result) {
data = result;
});
But my problem is that JVectorMap use the array in the following format
data_array = {
"US": 4977,
"AU": 4873,
"IN": 3671,
"BR": 2476,
"TR": 1476,
"CN": 146,
"CA": 134,
"BD": 100
};
but the returned JSON is in the following format
[{ "Key": "SA", "Value": 4 }]
How do I convert the above JSON to the following format so that JVectorMap could be populated.
data_array = {
"SA":4
}
Simply a matter of walking the array of inputs and create an object from each entry.
// set up some sample data - in your case you already have this.
var data = JSON.parse('[{"Key":"SA","Value":4},{"Key":"US","Value":12},{"Key":"BR","Value":6}]')
var obj={} // make a new object to build results.
for (var i =0; i < data.length; i = i + 1) {
obj[data[i].Key] = data[i].Value
}
// Note jquery only used for this debug output.
$("#output").html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>

JSON to HTML table using 'datatable' plugin

I'm trying to generate a HTML data table from the result of a SQL query execution. The resulting data is in JSON format. I'm using the plugin "Datatables" to achieve this. I'm following this example
I don't get an error but the data table is empty. I'm obviously doing something wrong or missing something.
Here's the code excerpt. Could I please get some guidance on to the right path please.
function jsDataPlot(chartProps) {
// Get the array from the element:
var graphPropsStore = chartProps;
// Loop through the array with the jQuery each function:
$.each(graphPropsStore, function (k, graphPropsStoreProperty) {
// The makeCall function returns a ajaxObject so the object gets put in var promise
var dbResAjx = getResultFromSql(k);
// Now fill the success function in this ajaxObject (could also use .error() or .done() )
dbResAjx.success(function (response) {
console.log(response);
// When success, call the function and use the values out of the array above
$('#divId').DataTable(response);
});
dbResAjx.error(function (response) {
console.log(response);
});
});
}
function getResultFromSql(paramId) {
// bla bla code
return $.ajax({
url: 'runMySqlQuery.php',
type: 'post',
data: {// some POST params}
});
}
JSON Result
[{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}]
OK, in your JSON yu have this. DATE - TYPE - NAME
[
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},
{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},
{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}
]
then in your JS should define your columns ....
$('#divId').DataTable({
columns : [
{data: "DATE"},
{data: "TYPE"},
{data: "NAME"}
],
data: response
});
example: https://jsfiddle.net/cmedina/7kfmyw6x/4/

How to parse json response in jQuery mobile?

I am new to jquery mobile. I am trying to get contact name from contacts. JSON by sending AJAX request. But I am not getting any alert when I click on submit button.
My jQuery ajax request
$(document).ready(function() {
//after button is clicked we download the data
$("#submit").click(function(){
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function(data) {
var json = $.parseJSON(data);
alert(json.name);
});
});
});
contacts.json
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
.
]
}
How to generate dynamic clickable list for above ajax response?
dataType: "json"
already specifies the returned data to be a json object. so to read the values, you can simply use the object syntax:
success: function(data) {
//cycle trough returned "contacts":
for(var i=0;i<data.contacts.length;i++){
console.log(data.contacts[i].name);
}
}
from the looks of it, your json will be an array of object. Try doing json[0].Name to test it
your json data present inside contacts,so you should take name in this format.
var json = $.parseJSON(data);
alert(json.contacts[0].name);
Firstly our code is badly formated (smart quotes, wrong placement of parentheses). Secondly since your contacts are in an array, you can't access them using json.name, you should try something like this instead:
$(document).ready(function () {
//after button is clicked we download the data
$("#submit").click(function () {
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
json.contacts.forEach(function(val, ind, arr){
alert(val.name);
});
}
});
});
});
In stead of parsing JSON you can do like followng:
$.ajax({
..
dataType: 'json' // using json, jquery will make parse for you
});
To access a property of your JSON do as shown in below:
data[0].name;
data[0].email;
Why you need data[0] because data is an array, so to its content retrieve you need data[0] (first element), which gives you an object {"name":"myName" ,"address": "myAddress" }.
And to access property of an object rule is:
Object.property
or sometimes
Object["property"] // in some case
So you need
data[0].name and so on to get what you want.
If you not
set dataType: json then you need to parse them using $.parseJSON() and to retrieve data like above.

FullCalendar: Using JSON feed containing a dynamic quantity of event sources

I have a case where I need to display multiple eventSources on a calendar, but don't know the quantity of sources until runtime. I've created a javascript function with an AJAX call to a PHP script to create a valid JSON feed (verified with an online tool), and am trying to drop that JSON data into the initialization of the calendar. I've tried it with FullCalendar 1.6.4 and 2.0.0 and it doesn't display any events or throw any errors. The odd part is I can copy the stringified version of the JSON feed into the eventSources and it works. Any ideas?
Here's the stringified JSON data:
[
{
"url": "/s/events.php?e=7",
"type": "GET",
"color": "#ffcc00",
"textColor": "#000000"
},
{
"url": "/s/events.php?e=59",
"type": "GET",
"color": "#ff6600",
"textColor": "#ffffff"
}
]
Heres the FullCalendar initialization code with the JSON data (dataSources not stringified):
function loadCal(dataSources) {
$('#calendar').fullCalendar({
eventSources: [
dataSources // Here's the JSON data
],
editable: true,
...
}
I've tried using the stringified version of dataSources and that results in an unusable URL (e.g., test.com/[%7B%22url%22:%20%22/s/events.php?e=7%22,%22type%22:%20%22GET%22,%22color%22:%20%22).
I'm open to suggestions of alternate approaches. Thanks.
Here's the code as I updated following the suggestion by Bhutto:
function loadCal() {
$('#calendar').fullCalendar({
eventSources: [
function() {
var userData = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
//console.log(userData);
var user_count = userData.length;
var source = [];
var jsonData = [];
// Create the sources
for (var i = 0; i < user_count; i++)
{
var uid = userData[i].uid;
if(!source[i]) source[i] = [];
source[i] = '/s/events.php?e=' + uid;
// Add each source to a JSON feed object
jsonData.push({
url: source[i],
type: 'GET',
color: userData[i].cal_color,
textColor: userData[i].txt_color,
error: function() { alert('There was an error loading calendar data.');}
});
}
console.log(jsonData); // In the console I can see well formed JSON data
return jsonData;
}
});
}
],
editable: true,

Categories

Resources