Weird issue where jQuery AJAX success data only parses last JSON node - javascript

So I have the following jQuery code:
function updateOrderSummary(orderID) {
var returnString = orderID;
$.ajax({
url: "library/getOrderSummary.php",
type: "POST",
data: ({returnString:returnString}),
success: function(data){
console.log(data);
}
});
}
When I run this script, the console shows the following JSON:
{"orderDetails":{"orderItem":{"itemName":"351","itemQuantity":"2","itemID":"5-5331fbfd5e0e7","costPerPlay":"2"},"orderItem":{"itemName":"Demo","itemQuantity":"1","itemID":"5-54067191b71e8","costPerPlay":"1"},"orderItem":{"itemName":"314","itemQuantity":"1","itemID":"5-5331f5b41f9f4","costPerPlay":"1"}}}
Formatted, it looks like this (for your convenience):
{
"orderDetails": {
"orderItem": {
"itemName": "351",
"itemQuantity": "2",
"itemID": "5-5331fbfd5e0e7",
"costPerPlay": "2"
},
"orderItem": {
"itemName": "Demo",
"itemQuantity": "1",
"itemID": "5-54067191b71e8",
"costPerPlay": "1"
},
"orderItem": {
"itemName": "314",
"itemQuantity": "1",
"itemID": "5-5331f5b41f9f4",
"costPerPlay": "1"
}
}
}
The JSON validates when I run it through JSONLint (jsonlint.com), but I can't seem to parse through the data when I add the dataType: "json" into my script. (ie:)
function updateOrderSummary(orderID) {
var returnString = orderID;
$.ajax({
url: "library/getOrderSummary.php",
type: "POST",
data: ({returnString:returnString}),
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
When I do this, my console only seems to show the last "node" of the JSON string that gets returned. And I can't seem to parse through it the way I normally do.
Ultimately, all I want to be able to do is get the number of "orderItems" that exist in the return string (in this case, 3), and display the "itemName" for each. So something like this:
for (var a = 0; a < numNodes; a++) {
returnString += data.orderDetails.orderItem[a].itemName;
}
Alas, nothing I do seems to let me drill down into the JSON.
Any thoughts?

change your json structure to below format. instead of object with same key(orderItem), group it as an array.
{
"orderDetails": {
"orderItem": [{
"itemName": "351",
"itemQuantity": "2",
"itemID": "5-5331fbfd5e0e7",
"costPerPlay": "2"
},
{
"itemName": "Demo",
"itemQuantity": "1",
"itemID": "5-54067191b71e8",
"costPerPlay": "1"
},
{
"itemName": "314",
"itemQuantity": "1",
"itemID": "5-5331f5b41f9f4",
"costPerPlay": "1"
}
]
}
}

The problem is your structure is set up as object with 3 identical keys.
Since object keys can't be identical the whole property gets over written ...leaving only the last one
Structure needs to be changed to array of objects
SOmething like this would be more appropriate
"orderDetails": [
{ "itemName": "351","itemQuantity": "2" ....},
{ "itemName": "567","itemQuantity": "34" ....}
]

Related

JSGrid Not show data from json

Hi I'm tryng to modify the "DataManipulation" example from jsGrid demos and I'm not able to show data from a json file retrived using a GET ajax call. Here's my controller code:
{
loadData: function (filter) {
var data = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json",
url: "myFileURL.json",
dataType: "json"
}).done(function(response){
console.log(response);
data.resolve(response);
});
return data.promise();}
The json retrived is like this
{"98762":{"Address":"Address 1","Age":1,"Country":1,"Married":false,"Name":"Name1"},"637399":{"Address":"Address 2","Age":2,"Country":2,"Married":true,"Name":"Name 2"},"234567554":{"Address":"Address 3","Age":3,"Country":3,"Married":true,"Name":"Name"}}
Your json is not well formed. jsGrid expects a list of objects as a return type. Use this instead.
[
{
"Address": "Address 1",
"Age": 1,
"Country": 1,
"Married": false,
"Name": "Name1"
},
{
"Address": "Address 2",
"Age": 2,
"Country": 2,
"Married": true,
"Name": "Name 2"
},
{
"Address": "Address 3",
"Age": 3,
"Country": 3,
"Married": true,
"Name": "Name"
}
];
This is with the assumption that the schema of the json is correct. Good luck!

Sort array by timestamp in jquery

In AJAX response I am getting JSON array with multiple nodes. How can I sort every node by its time stamp .
Code I tried:
$$.ajax({
type:'POST',
url: "http://www.xyz.co/get_all_news.php",
dataType: "JSON",
data:{'email': window.localStorage["email"], 'business_id': localStorage.getItem("business_id")},
success: function (jsondata1){
data= JSON.parse(jsondata1);
jsondata1.sort(function(x, y){
return x.created_at - y.created_at;
})
console.log(jsondata1); //Error - Uncaught TypeError: jsondata1.sort is not a function
}
});
Also value of jsondata1 is
var jsondata1 = [
{"id":"1","body":"Bsjd djjdjd jdjdkd djjdjd jdjd","votes":"4","update_type":"7","created_at":"2015-11-21 02:03:41","name":"Nehil"},
{"id":"2","body":"#TestingBestNominations","votes":"1","update_type":"7","created_at":"2015-11-21 02:03:44","name":"Nehil"},
{"id":"1","name":"#milestone1","date":"0000-00-00","location":"Mumbai","story_body":"Hdjjdjdbj djfjjd djkdjd","short_link":"A0Ijv","created_at":"2015-11-19 05:09:41","path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451447934978817.jpg","update_type":"3"},
{"id":"1","name":"Product 1","description":"Dbbxbxjjd fjkd","short_link":"CmR0X","created_at":"2015-11-19 05:28:34","path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451447936111369.jpg","update_type":"4"}
]
Sorting it by (created_at) Error I am getting is
"Uncaught TypeError: jsondata1.sort is not a function".
You can treat date strings (in this case as ISO format) as string and sort it with String.prototype.localeCompare.
var jsondata1 = [
{ "id": "1", "body": "Bsjd djjdjd jdjdkd djjdjd jdjd", "votes": "4", "update_type": "7", "created_at": "2015-11-21 02:03:41", "name": "Nehil" },
{ "id": "2", "body": "#TestingBestNominations", "votes": "1", "update_type": "7", "created_at": "2015-11-21 02:03:44", "name": "Nehil" },
{ "id": "1", "name": "#milestone1", "date": "0000-00-00", "location": "Mumbai", "story_body": "Hdjjdjdbj djfjjd djkdjd", "short_link": "A0Ijv", "created_at": "2015-11-19 05:09:41", "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451447934978817.jpg", "update_type": "3" },
{ "id": "1", "name": "Product 1", "description": "Dbbxbxjjd fjkd", "short_link": "CmR0X", "created_at": "2015-11-19 05:28:34", "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451447936111369.jpg", "update_type": "4" }
];
jsondata1.sort(function (a, b) { return a.created_at.localeCompare(b.created_at); });
document.write('<pre>' + JSON.stringify(jsondata1, 0, 4) + '</pre>');
For different date type I suggest to have a look here: Sort Javascript Object Array By Date

Sorting an array of JavaScript objects by sub array property/value

I have the following data being returned from a server (the structure of this data is something that I do not have control over)...
var data = {
"TrackingResults": [
{
"Name": "Pack One",
"Products": {
"Product": [
{
"ProductName": "Soccer Ball"
},
{
"ProductName": "Tennis Racket"
},
{
"ProductName": "Gold Putter"
}
]
},
"status": "Despatched",
"Location": "Alabama",
"Type": "Parcel"
},
{
"Name": "Pack Two",
"Products": {
"Product": [
{
"ProductName": "Backet Ball Hoop"
},
{
"ProductName": "Base Ball Glove"
}
]
},
"status": "Despatched",
"Location": "Florida",
"Type": "Parcel"
}
]
};
I would like to be able to sort each Tracking Result by the first Product Name. I can't find any code that will sort by a sub array property/value.
You should use the Array.sort method with a custom comparator function:
var resultsComparator = function (res1, res2) {
var prod1 = res1.Products.Product[0].ProductName;
var prod2 = res2.Products.Product[0].ProductName;
return prod1.localeCompare(prod2);
}
This way the ordering is based on the current locale of the web browser. You just pass the function to the sort method:
data.TrackingResults.sort(resultsComparator);
You need to write it manually like: (with the hint on localeCompare from meskobalazs's comment)
var result = data.TrackingResults.sort(function(a,b){
return a.Products.Product[0].ProductName.localeCompare(b.Products.Product[0].ProductName)
});
This should work for sorting TrackingResults

How to map this array into a new format with JavaScript

I know there is some functional programming in JavaScript and I am wondering if I can create a function like so using some functional methods easier than just writing the code up myself the procedural way (as you can see below, I am also having some SO formatting issue for some reason).
function mapToFormat(var myarray, var colname) {
}
myarray is actually the following json from a server response...
{
"time": "1",
"col1": "2",
"col2": "3",
"col3": "1"
},
{
"time": "2",
"col2": "3"
},
{
"time": "3",
"col1": "3"
},
{
"time": "4",
"col3": "3"
},
{
   "time": "5",
   "col1": null
}
I would like to call the function on the above json like so
mapToFormat(myarray, 'col1')
and then have it return data like so (in an array format though)
{
"time": "1",
"col1": "2"
},
{
"time": "3",
"col1": "3"
},
{
   "time": "5",
   "col1": "null
}
I am thinking maybe I just use
var newData = [];
$.each(data, function (index, value) {
if(value[colname] not exist) {
newData.push({
"time": value['time'],
colname : value[colname]
}
});
});
but I am not sure how to tell the difference between "col1" not being there and "col1" : null as I want to pass through any null values that come through as well.
How I can achieve this? And I am wondering if there is a map function or something I should be using that might be better?
Try this (fiddle: http://jsfiddle.net/GNr8N/1/):
function mapToFormat(myArray, col) {
return myArray.map(function(record){
var result = {
time: record.time,
}
if (typeof record[col] !== 'undefined') {
result[col] = record[col]
}
return result;
})
}
The !== operator does not do type casting, so if record[col] exists, it will be added, even if it is null.

Retrieving and displaying JSON data from URL

I am trying to retrieve and display information about current weather from a JSON object using javascript and a URL request:
http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'
the data from the URL looks like this:
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"humidity": "88",
"observation_time": "03:30 PM",
"precipMM": "2.7",
"pressure": "1008",
"temp_C": "12",
"temp_F": "54",
"visibility": "8",
"weatherCode": "302",
"weatherDesc": [
{
"value": "Moderate rain"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "140",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "DE3",
"type": "Postcode"
}
],
"weather": [
{
"date": "2012-05-09",
"precipMM": "11.8",
"tempMaxC": "13",
"tempMaxF": "56",
"tempMinC": "12",
"tempMinF": "53",
"weatherCode": "266",
"weatherDesc": [
{
"value": "Light drizzle"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "141",
"winddirection": "SE",
"windspeedKmph": "12",
"windspeedMiles": "7"
},
{
"date": "2012-05-10",
"precipMM": "11.1",
"tempMaxC": "18",
"tempMaxF": "64",
"tempMinC": "6",
"tempMinF": "43",
"weatherCode": "353",
"weatherDesc": [
{
"value": "Light rain shower"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "209",
"winddirection": "SSW",
"windspeedKmph": "30",
"windspeedMiles": "19"
}
]
}
}
I have tried a couple of scripts to try and get the data and take bits out to display in a div. The first one looks like this:
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
dataType: 'json',
success: function(data) {
jQuery.each(data, function() {
alert("HELLO");
alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
alert("Current Humidity = " + this.data.current_condition.humidity);
});
}
});
the second one looks like this:
var postcode = document.getElementById("address").value;
function getWeather(userName, count) {
$.getJSON(
'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805',
{},
showWeather,
//'jsonp'
);
}
function showWeather(day) {
var str = '<ul>';
str += '<h2>Tweets from ' + postcode + '</h2>';
var i = 0;
$.each(day, function(index, value) {
if (i == count) return;
var dt = new Date(value.date);
str += '<p>';
str += value.temp_C; //gets "text" from JSON
str += '</p>';
str += '';
str += '';
i++;
});
}
I want to get the weather information from the JSON URL and display some of the information in a div, can anybody explain how to do this is these two scripts dont work.
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805",
dataType: 'jsonp', // You need to use 'jsonp' here because it is cross domain request
success: function(data) {
$.each(data, function(index, value) {
alert(value.current_condition[0].cloudcover);
alert(value.current_condition[0].humidity);
alert(value.current_condition[0].weatherDesc[0].value);
alert(value.request[0].query);
alert(value.request[0].query);
$.each(value.weather, function(i, val) {
alert(val.precipMM);
alert(val.weatherDesc[0].value);
})
});
}
});
DEMO
There are a few problems... the following should work (modification of the first block of code).
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805&callback=?",
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert(JSON.stringify(this));
alert("Current Cloud Cover = " + this.current_condition[0].cloudcover);
alert("Current Humidity = " + this.current_condition[0].humidity);
});
}
});
To recap:
You need to use JsonP to circumvent cross-site-scripting restrictions (do that by adding "&callback=?" to the AJAX URL.
The root of the JSON response is data, so you need to write data.data.
The current_condition property is an array-- have to add an indexer (ie, [0]) to access it.

Categories