Why is jQuery.getJSON structured the way it is? - javascript

Why is the getJSON function structured this way?
$.getJSON( url [, data ] [, success ] )
Instead of just returning an object, i.e.:
var myjson = $.getJSON( url [, data ])

Because it returns a jqXHR object that contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible. Basically, how would you know if the request was successful?

Related

How these arguments of ajax function work?

I am whatching a tutorial that has the following code
But I can't understand what are url, cache and success? Are they arrays? How do they work?
You can find below the explanations:
cache
Type: Boolean
A Boolean value indicating whether the browser should cache the requested pages. Default is true.
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters.
url
Type: String
Specifies the URL to send the request to. Default is the
current page
success(result,status,xhr)
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be run when the request succeeds
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
Everything is explained in the jQuery.ajax() Documentation

Pass JSON in Javascript variable into a JQuery post

I am trying to get some data from a remote location by a JQuery post. It works great when I hardcode the data to post, but doesn't work when I put the JSON in a javascript variable, and then pass it in. As far as I understand, a JSON is just a string, so I'm not sure what the difference is.
so, this works:
$.post( PostURL, {var:"somevalue"}, function( data ) {
// do something with data
}
but this doesn't:
jsonstring = '{var:"somevalue"}';
$.post( PostURL, jsonstring, function( data ) {
// do something with data
}
obviously, I'm going to need to send different variables to get the stuff I need, so it can't be hard-coded. What am I doing wrong?
Data in post() doesn't take JSON as an argument but an object, which is why the first code works. Your second code is using JSON, which is a string representation of an object rather than an actual object, therefore invalid.
jQuery.post( url [, data ] [, success ] [, dataType ] )
url
Type: String
A string containing the URL to which the request is sent.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
http://api.jquery.com/jquery.post/
Note that while it says that data can take a string, it is of the form key=value&key=value.
You don't need JSON, simply store the object in your variable rather than converting it to a string.
var myData = {var:"somevalue"};
$.post(PostURL, myData, function(data) {
// do something with data
});
jsonstring = JSON.parse('{var:"somevalue"}');
$.post( PostURL, jsonstring, function( data ) {
// do something with data
}

Converting JSON using jQuery

For reference, this is the JSON I'm working with: http://goo.gl/xxHci0
In regular JavaScript, using the code below works fine and I can manipulate it easily:
var info = JSON.parse(document.getElementsByTagName("pre")[0].innerHTML);
alert(info[0]["AssetId"]);
But I'm working on a jQuery version of the same code to avoid using methods like iFrames to get this data. My jQuery function is:
$.get (
page,
function parse(data) {
var r = $.parseJSON(data);
alert(r[0]["AssetId"]);
}
);
I found ways to convert the JSON using jQuery, but I'm having trouble finding where the JSON code is that needs to be converted.
Provided that the response from the server is a valid string representation of a JSON object, you'll be able to specify the dataType for the get() request. You could do something like this:
$.get( page, function( data ) {
alert( data[0]["AssetId"] );
}, "json" ); // <-- here is the dataType
With the correct dataType set, you will not need to manually parse the data, it will arrive in your callback function as a JSON object.
References:
$.get()
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
You can use getJson. This converts your JSON string to a JavaScript object.
I threw JSFiddle together for you using the facebook graph api:
http://jsfiddle.net/J4LCX/
$.getJSON( "http://graph.facebook.com/spikeh/",
function( data ) {
alert(data.id);
});
Alternatively, to fix your code, just reference the object's id directly:
$.get (
"http://graph.facebook.com/spikeh/",
function parse(data) {
alert(data.id);
}
);
JsFiddle: http://jsfiddle.net/LBy9y/

not sure why this jquery post isn't working

I have the following jquery:
var xj=[{"name":"person","id":1},{"name":"jack", "id":2}];
$.post('/hex-jt/locations',xj , function(data){
console.log("this posted");
},'json');
which seems like it should be ok. But it is passed like this to my rails app:
Any idea what is going on with this?
You are calling jquery.post() with bad argument data, passing an array instead of a String or a PlainObject.
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
You can for instance modify it like this, wrapping the array in an object:
xj={"users":[{"name":"person","id":1},{"name":"jack", "id":2}]};

jQuery Deferreds & Ajax - how to access the jqXHR object?

In the jQuery docs regarding Deferreds, there's this example of returning ajax args including jqXHR:
$.when( $.ajax("test.php") ).then(function(ajaxArgs){
alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});
But it seems that the docs are wrong. ajaxArgs is actually the response from the $.ajax call.
I need to get access to the jqXHR object because I need some meta data about the actual call, but it seems to be pretty hackish. This is what I'm currently doing, but there's got to be a better way (crossing my fingers).
xhr = $.ajax({
'url': src,
}).done(function () {
var meta = xhr.getResponseHeader(...);
});
What's the best/easiest way to get access to the jqXHR data that I need?
Use the third argument:
.then(function(text,status,xhr) {
var meta = xhr.getResponseHeader(...);
});
Note however that if you pass multiple deferreds into $.when, it'l be the 3rd index of the first argument, second, or third depending on which request you want the headers of.
$.when( $.ajax("test.php"),$.ajax("test.php"),$.ajax("test.php") ).then(function(){
var meta1 = arguments[0][2].getResponseHeader(...);
var meta2 = arguments[1][2].getResponseHeader(...);
var meta3 = arguments[2][2].getResponseHeader(...);
});

Categories