jQuery+AJAX+JSON

update: I really should RTFM. dataType can go in any place when listing options. If I had read the docs a bit more carefully, I would’ve noticed that the reason I started getting a JSON object back instead of a XMLHttpRequest is that I specificed ‘success’ with a callback instead of ‘complete’.

Though I did figure out a better way of parsing the returned object

var myCallback=function(jsonObj){
for (k in jsonObj) {
if (iWantToCheck(k)) {
useValueOfK(jsonObj[k]);
}
}
}

Found out something interesting today. I normally try to stick to a simple AJAX return such as html or xml that is easy to manipulate. Today, I couldn’t accomplish my task without the help of JSON. I’m sure there’s other ways I could’ve told JS how to react on different succeed or fail conditions but JSON was the first one that came to mind. On to the story…I set the dataType on my ajax options to ‘json’ and was surprised to find that I was still getting a XMLHttpRequest object instead of the expected JSON object. I tried sending ‘Content-Type: application/json’ header, tried a bunch of other things I can’t remember at the moment.

I eventually discovered that in order for jQuery to return a JSON object from an AJAX call, dataType needs to be specified before data in the options.

correct:

$.ajax({
url:myHappyURL,
dataType:"json",
data:$("#formSauce").serialize(),
type:'post',
success:processResponse
});

INCORRECT

$.ajax({
url:myHappyURL,
data:$("#thisWillFailToReturnJSON").serialize(),
type:'post',
dataType:"json",
success:processResponse
});

Otherwise, even if you specify a MIME type, you will get a XMLHttpRequest object and not the expected JSON object.

After that, I had to remember how to parse a JSON object. Parsing the JSON object turned out to be easier than I thought. It’s as simple as jsonObj.property1. Part of my JSON return was a single dimensional array. Being the lazy programmer that I am, I didn’t want to do jsonObj.arrayProp[0] (which I’m not sure actually works b/c I’m taking a guess at it). I could’ve iterated through with a loop but was sure that jQuery had to have a way of dealing with this. After a bit of searching through documentation and trying to find the answer through Google, I pieced together

$.each(jsonObj.arrayProp,function (k,v) {doStuffwith(v);});

0 comments on “jQuery+AJAX+JSONAdd yours →

Leave a Reply