Parse Json data in Jquery - javascript

I am new to Jquery, Ajax and JSON.
I am facing issue with the parsing of Json data.
I have been through many questions on stackoverflow
Parsing JSON objects for HTML table
Access / process (nested) objects, arrays or JSON
Parse JSON in JavaScript?
How could I parse through this JSON object in JQuery?
and many more...
Still I am not able to parse the Json data.
My Jquery Looks like :
$.ajax({
/* type : "POST", */
url : "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data : "processDateInput="+processDate,
dataType : "json",
async: true,
success : function(result) {
var od = JSON.stringify(result) ;
var obj = JSON.parse(od);
console.log(obj.od);
console.log(obj.od.percentageCompleted);
console.log(od);
$.each(JSON.parse(od), function(idx, obj) {
console.log(obj.tagName);
});
}
});
I have tried all the combinations to parse this data, but the js console print as "undefined"
I am able to print the json object as :
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"10/11/2014",
"11/11/2014",
"12/11/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"remainingTime": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
Please help me how can I fetch dateProcessed array and percentage complete.

Try this code.
$.ajax({
/* type : "POST", */
url: "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data: "processDateInput=" + processDate,
dataType: "json",
async: true,
success: function (result) {
var od = JSON.stringify(result);
var obj = JSON.parse(od);
$.each(obj, function (index, value) {
console.log(obj[index][0].percentageCompleted);
console.log(obj[index][0].processRunning);
console.log(obj[index][0].remainingTime);
console.log(obj[index][0].successBatchCount);
console.log(obj[index][0].totalBatchCount);
console.log(obj.processDateInput);
$.each(obj[index][0].dateProcessed, function (ind, val) {
console.log(val);
})
});
}
});

When you specify the dataType as JSON, jQuery will automatically parse it for you. Parsing it again as you are (multiple times, even) will cause issues. Try this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
}
I'm not entirely sure what your $.each loop is trying to do as there is no tagName property in your object.

What is the is the return data of your AJAX call
is like this then
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"09/12/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
you can parse it like this
var json = JSON.parse(result);
var od = json['od'];
var processDateInput = json['processDateInput'];
$.each(od, function(index, value){
console.log(value, index);
});
hope it would work on you.

no need of parsing it because you have already mentioned it as json you can simply do like this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
console.log(od);
$.each(result, function(idx, obj) {
console.log(obj[0].dateProcessed);
});
}

Related

Use form naming to reach json data in Javascript/jQuery?

I have the following input name: dynamic[elements][1][slider][image1]
When performing an ajax call, a json response with settings and its value is returned.
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
});
How can i get the value of dynamic[elements][1][slider][image1] the easiest way? It works to get the value like this:
data.dynamic.elements[1].slider.image1
So:
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data.dynamic.elements[1].slider.image1);
});
But isn't their any better way of getting the value? The only identifier I have to get the value, is the name of the input field which is dynamic[elements][1][slider][image1]. So i would need to extract this string and put it together as data.dynamic.elements[1].slider.image1 to then make it a dynamic variable somehow (to finally get the value)?
Example ajax response:
{
"success": 1,
"dynamic": {
"elements": [
{
"title": {
"title": "Our beautiful topic"
}
},
{
"slider": {
"image1": "5zw3ucypzp3qham.png",
"image1_link": "hellor"
}
}
]
}
}
You may choose to write a generic function for the purpose of retrieving data from object. The function should look something like below. Though the function may not be foolproof but should be enough for proof-of-concept.
function getObjectData(target, path) {
// if the path is not in dot notation first convert
if (path.indexOf(".") == -1)
path = path.replace(/\[/g, ".").replace(/\]/g, "");
var parts = path.split(".");
return parts.reduce(function (acc, currentVal) {
return acc ? (acc[currentVal] || undefined) : acc;
}, target);
}
//usage
getObjectData(data, "dynamic.elements.0.slider.image1"); //undefined
getObjectData(data, "dynamic.elements.1.slider.image1"); //5zw3ucypzp3qham.png
getObjectData(data, "dynamic[elements][1][slider][image1]"); //5zw3ucypzp3qham.png
Hope this helps.

Edit data in an ArcGIS Service via rest and json with jquery/javascript

i'm trying to change information from a feature from an arcgis service via rest and json. I have made a function that will be called but the result is giving me no idea what to do.
I'm using openlayers3 as well and i know it has the function feature.setProperties but i`m not sure how to actually put that towards a service. i have checked this example to understand it:
http://openlayers.org/en/latest/examples/vector-esri-edit.html?q=arcgis
but sadly i do not, because i can't create the payload variable.
But if there is a way to do it with openlayers3 i`m even happier.
The code i use is:
export function changeFeature(feature) {
var str = {};
str = feature.getProperties();
for (var s in str) {
if (typeof str[s] === 'object') {
} else {
str[s] = document.getElementById(''+s + '1').value;
feature[s] = document.getElementById(''+s + '1').value;
}
};
console.log(str);
$.ajax({
type: "POST",
url: "http://192.168.216.56:6080/arcgis/rest/services/test/MyMapService/FeatureServer/0/applyEdits",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And the console will give me this:
Object { geometry: Object,
objectid: "56400",
relcp86d_: "0",
relcp86d_i: "564",
symbol: "4",
polygonid: "0",
scale: "1",
angle: "0",
omschrijvi: "Rosmolen" }
which looks okay but then it throws me this error:
TypeError: event is undefined[Meer info]
here is an Esri documentation to use Applyedit: http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/fsedits.html
so to update a feature, you have to send a json with two objects :
one is the geometry, which contains the X,Y coordinates of the feature
the other is the attributes, with the OBJECTID key-value pair, and other attributes pair to update.

Jquery send Json data not working

I want to sent some JSON data with ajax this is my script
$(document).ready(function () {
jsonObj = [];
$('.img-bg').map(function () {
var self = this;
var next = $(this).nextAll('.rectangle');
if (next.length > 0) {
next.map(function () {
item = {};
item.src = self.src;
item.left = $(this).css('left');
item.height = $(this).css('height');
jsonObj.push(item);
});
}
});
var data={ "firstName" : "Ray" };
jsonString = JSON.stringify(jsonObj);
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: jsonString,
success: function(response) {
console.log(response);
}
});
});
</script>
And jsonObj gives
[Object, Object, Object]
0: Object
height: "341px"
left: "10px"
src: "http://localhost/docAuto/test.jpg"
__proto__: Object
1: Object
height: "321px"
left: "54px"
src: "http://localhost/docAuto/image.jpg"
Output of jsonString
[{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}]
Both var is not send, but if I send data it's working. My Json file is wrong?
You need to pass the options to data as an object. Here's a fixed $.ajax call:
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonString },
success: function(response) {
console.log(response);
}
});
Your testajax.php should now see the jsonString in URL variable json.
edit: fixed my response. I misread your code due to the problems with indentation.
You don't need to use JSON.stringify to send a json object via the jQuery $.ajax() method... jQuery will take care of that conversion behind the scenes. Just use jsonObj as your data parameter.
You need to use POST in upper case.
I think your JSON is missing the key part. When I added the key: 'first', it worked. You got one mighty Json Array there:
JSON.stringify({ first: [{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}] })
JSFiddle link http://jsfiddle.net/jyrkim/suvG7/1/
Json Arrays, syntax etc link

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Cannot copy object property in javascript

I have an ajax call which gathers the parent and child dependencies for some entities. Inside the success function I assign what ajax returns (data) to a global level object.
$.ajax(
{
type: "POST",
url: 'ajax_handler.php',
data: {action:'get_dependencies', relation:relation, 'jobs[]':jobs, project:project},
dataType: 'json',
async: false, //do not change
success: function(data)
{
for(var key in data)
{
if( data.hasOwnProperty(key) )
{
//Copy data object to document level existingDependency object
existingDependency[key] = data[key];
}
}
},
error: function(xhr)
{
alert('error2:'+xhr.responseText);
}
});
I call this AJAX which is in a function twice. One for parents and one for children. I figured that this line existingDependency[key] = data[key]; is reassigning the object thus the previous assignment is lost. In other words the existingDependency object cannot hold both ['parent'] and ['child'] properties together.
To fix this I did the below changes so that existingDependency holds both properties:
success: function(data)
{
for(var key in data)
{
if( data[key].hasOwnProperty(relation) )
{
//Copy data object to document level existingDependency object
existingDependency[key][relation] = data[key][relation];
}
}
}
But this does not work at all. existingDependency object is empty. Below alerts empty.
var keys = '';
for(key in existingDependency)
{
keys += key+'\n';
}
alert(keys);
Any ideas why this assignment existingDependency[key][relation] = data[key][relation] does not work? data[key][relation] holds an array if it makes any difference.
Use extend:
$.ajax({
type: "POST",
url: 'ajax_handler.php',
data: {
action:'get_dependencies',
relation:relation,
'jobs[]':jobs,
project:project
},
dataType: 'json',
async: false, //do not change
success: function(data) {
$.extend(true, existingDependency, data);//this will copy/merge "data" into "existingDependency". properties from "data" that also exist in "existingDependency" will be overwritten with those from "data".
},
error: function(xhr) {
alert('error2:'+xhr.responseText);
}
});
As for why eD[key] = data[key] works while eD[key][relation] = data[key][relation] does not its hard to say without being able to run your code and debug it. But if eD[key] did not yet exist yet then it would not be able to add "relation" to it. A possible fix for that would have been:
if (!eD.hasOwnProperty(key)){
eD[key] = {};
}
eD[key][relation] = data[key][relation];

Categories