How to process JSON output in AJAX? - javascript

I have this code snippet in .js file
$(function () {
// KeyDates
var url = "http://localhost:8732/Design_Time_Addresses/Intel.IIP.MDF.WCF/ProgramCalendarService/GetKeyDatesCalendarNew";
$.ajax({
url: url,
data: null,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (GetKeyDatesCalendarDataNew) {
alert(GetKeyDatesCalendarDataNew);
$(document).ajaxStop($.unblockUI);
}
});
});
How do i process the key value pair in GetKeyDatesCalendarDataNew?

You probably want to know how to access an object's props. For that, use the for in loop to iterate over the object's values:
success: function (GetKeyDatesCalendarDataNew) {
for(var key in GetKeyDatesCalendarDataNew)
{
var value = GetKeyDatesCalendarDataNew[key];
// do somehitng based on the key and/or value iterated
}
}

For this case, the argument of the success function is the evaluated JSON that was returned from the Ajax request. Therefore GetKeyDatesCalendarDataNew, which you should rename to something like data, becomes the actual data that your server returned.
You can only process the data if you know its structure. One simple way of knowing this would be to do console.log(GetKeyDatesCalendarDataNew) and then easily process it with a for loop if it's an array or for x in.. if it's an object.

You can use JQuery "getJSON" function where you need to pass the url and specify a callback function.Your ajax call will be handled by the getJSON function. In the callback function, you can access the Keys as properties. A nice example
Lav G

$.each(GetKeyDatesCalendarDataNew,function(key,value){
//do something here
})

Related

Pass object value to controller using Ajax GET

$.ajax({
url: "/Course/GetChapters/",
type: "GET",
data:{id:2},
beforeSend: function () { },
success: function (result) {}
})
.done(function () {});
Can i pass a complex object via data?
JQuery Ajax - Documentation
Data -> Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So as long as you have simple name/value pairs it should work. Of course the length of the URL is limited to 2,083 characters.
try this:
var data = 'param1=' + value+ '&param2=' + value;
OR
var data = '{param1:'val1',param2:'val2',}'.

Intercept and modify JSON string before jQuery.getJSON() does its thing

I use jQuery's getJSON call to rerieve the content from a file called my.json.
Now sometimes the JSON file contains a certain character, that would invalidate the syntax. Unfortunately, it is not in my power to change that.
I thought it would be easy to use the success thing to intercept the JSON string and dix it, before $.getJSON() reads it and fails because the syntax is invalid. Obviously, it's not as easy, as I thought.
I would appreciate, if someone could help me out fixing below code.
$.ajaxSetup({
beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}},
cache: false
});
$.getJSON("my.json", function(data){
// Do something with the JSON
console.log("JSON object: " + data);
}).success(function(data, textStatus, jqXHR) {
// Intercept JSON string and modify it.
var fixed_json = fix_json(jqXHR.responseText);
jqXHR.responseText = fixed_json; // Obviously not as simple as I thought.
});
You can use the success callback of $.ajax() to do the required check on the returned data. It would require you to set the dataType to text though, so that jQuery doesn't try and automatically parse it for you. Try this:
$.ajax({
url: "my.json",
dataType: 'text',
success: function(data) {
var obj;
try {
obj = JSON.parse(data);
}
catch(e) {
obj = fix_json(data);
}
// work with the object here...
})
});
Example fiddle
Depending on the work that fix_json does, and assuming that it always returns an object, you could call that directly and remove the try/catch.

Accessing JSON string Outside of Jquery Ajax Call

I am wondering is these is any way to access the results of a jquery ajax call in the form a traditional var set to function fashion. For example consider:
function getPoints(){
//An array of JSON objects
var Points;
$.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
}).done(function(data){
//console.log(data);
Points.append(data);
});
console.log(Points);
return Points;
}
The commented out console.log show the array of json objects whereas the outer one does not. Now, i have tries this:
var Points = $.ajax({ ...});
And i see the response text within a larger object, but am unsure how to access the responseText. console.log(Points.responseText) yields an undefined variable.
Is this possible with this approach? Here is another question that received a check mark with a similar issue.
I have another solutions, which is the encapsulate my code within the done() function and i will have access to all my data. I was just curious if what i am attempting to do is even doable.
Thank you.
yes it is possible, however, you must wait for the request to be complete before doing so. However, since you can't effectively force the return to wait until the data exists, you're only options are to return a deferred object instead, or re-write the function in such a way that allows it to accept a callback.
function getPoints(){
return $.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST'
});
}
getPoints().done(function(data){
console.log(data);
});
or
function getPoints(callback){
return $.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
success: callback
});
}
getPoints(function(data){
console.log(data);
});
Because the Ajax call is done asynchronously you shouldn't return it from the outside function. This would require that you somehow block until the asynchronous call completes. Instead you could pass in a callback function to the getPoints function that will handle the logic of using the points.
function getPoints(callback){
$.ajax({
url: "js/retrievePointsDataJson.php",
dataType:'json',
type: 'POST',
}).done(function(data){
callback(data);
});
}
The asynchronous nature of ajax can make things harder if your used to imperative programming, but it will make your user interface much more responsive.
The log you're calling in the outer function is working with an undefined variable because the function is asynchronous. You can't return it from getPoints because it won't have finished. Any work with the Points variable needs to happen inside the callback (the function passed to done).

Why is jQuery.ajax() Calling my Objects Functions?

I'm having an issue where jQuery.ajax() is calling my data objects functions. For example, I have an object structure similar to the following:
var TestFactory = (function () {
var _id;
var _attributes;
return {
createObject: function (objectId) {
var value = null;
_id = objectId;
_attributes = {};
function _showErrorStatus() {
$('label')
.css('background-color', 'red')
.css('color', 'black')
.text('jQuery called me...');
}
function _attr(key, value) {
if (value == null) {
return _attributes[key];
}
_attributes[key] = value;
return this;
}
return {
id: _id,
attributes: _attributes,
showErrorStatus: _showErrorStatus,
attr: _attr,
}
}
}
})();
I'd like to use this object as the data value for my jQuery.ajax() call, as follows:
var myObject = TestFactory.createObject(12345);
myObject.attr('name', 'Fred Flinstone');
$.ajax({
url: '/echo/json/',
type: 'GET',
data: myObject,
dataType: 'json',
});
The issue I'm running into is jQuery.ajax() is calling the showErrorStatus() function from the object returned by the factory --nowhere in my code do I call this function.
I like the OOP qualities I get out of using this object, so is there any way to handle this case without a significant rewrite (e.g., dropping all my functionality from the "class")?
NOTE: I found it difficult to explain this problem, so here is a complete running example on jsfiddle.
Use JSON.stringify (not a jQuery method).
$.ajax({
url: '/echo/json/',
type: 'GET',
data: JSON.stringify(myObject),
dataType: 'json',
});
http://jsfiddle.net/HJ9AS/10/
It happens because it's a feature, though not documented as far as I can tell.
If you pass an object, then it assumes you want it to call any functions that are values of object properties.
One way of doing it is to use a function like Underscore's pick(). It can be used to cherry-pick certain properties you need from the object. It is a useful library anyways, but you can also implement this simple method if you wish.
$.ajax({
url: '/echo/json/',
type: 'GET',
/* only send id and attributes! */
data: _.pick(myObject, 'id', 'attributes'),
dataType: 'json',
});
It might be a nice habit to always whitelist stuff, not just send everything blindly. Specifying exactly what to send can save you from future surprises (like the one you just encountered). Most of the time you simply don't want to send everything that is stored in your object.
You can also implement some way for your object to be able to return its sendable contens. It could get a .getJSON() method that just collects from the object everything to be sent.
Concerning the function calling:
Processing the data property uses $.param(), which has this in the docs:
As of jQuery 1.3, the return value of a function is used instead of the function as a String.
This is a feature, not a bug :). I understand the logic behind it, because if there is a function in the object that you just specified as data to be sent, there must be a good reason behind it...
Instead of passing data: myObject,
try setting this: var serializedObject = myObject.param()
then passing data: serializedObject
Check out jQuery's param function here.

$.ajaxSetup global data doesnt merge in load function

I would like to set a global data parameter for all my ajax requests
$.ajaxSetup({
data: {hash : "12345"}
});
after setting this I call:
var myData = {
name : "John",
age : "28"
}
$.get(url, myData, function(data){
...
});
this works fine and add all 3 parameters (hash, name, age) to request data
but when I call load function instead of get, it doesnt work and I get only 2 parameters (name, age):
$("#my_div").load(url, myData, function(data){
...
});
please could anyone tell me why it doesnt work for load function? I have many usages of load function in my app and I dont want to change load on get
thank you for every tip!
This could be considered a bug in jQuery; or at the very least, they should accept the interface between their AJAX methods are inconsistent.
The only way to fix this is by using jQuery.extend to merge the default data with the data you've provided:
jQuery.extend(myData, jQuery.ajaxSettings);
Before making the request.
How its a bug:
load converts the data object into a string before passing in onto the underlying jQuery.ajax method, where as get doesn't.
Because of this, when ajaxExtend builds the data object, in the load scenario the data parameter is set to the string, whereas with get the data object is merged with jQuery.ajaxSettings.
If you take a look at .load, you'll see it does not pass an object to .ajax, even if you pass one to .load:
if ( params ) {
...
} else if ( typeof params === "object" ) {
// it will execute this
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
It will call jQuery.params, which returns a string, and the object cannot be merged with the string. So it will send "name=John&age=28" without combining the hash object.
This is not the case for $.get, because that function directly passes the object:
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
...
return jQuery.ajax({
type: method,
url: url,
data: data, // passed directly to $.ajax which takes care of merging $.ajaxSetup stuff
success: callback,
dataType: type
});
};
});

Categories

Resources