How to deal with response data in ajaxComplete event - javascript

Say I have this code:
function onComplete(event, request, settings)
{
// How do I get the data? In the correct format?
}
$('body').ajaxComplete(onComplete);
In regular ajax success handlers, I can just access the data directly since it will be the first parameter to the handler. It will also be in the correct format (as long as the content-type was set right on the server).
How do I deal with the data on the ajaxComplete event?

You can use it like this, but it's not documented:
function onComplete(event, request, settings) {
var data = $.httpData(request, settings.dataType, settings);
}
The jQuery.httpData function is what's used internally to get data for the success handler, but you can use it directly. Please be aware that it is undocumented, and therefore subject to change without notice in new releases. For example in jQuery 1.4.3, it will be jQuery.ajax.httpData instead.

According to the the doc:
http://api.jquery.com/ajaxComplete/
I don't think you mean to fiddle with the data, because it doesn't pass any data to the handler. If you want data you better off using the set success property in regular Ajax.

This may not be the right handler to use if you want to get data as this is really intended more as a basic notification callback (for all hooked elements) when any AJAX calls completes.
To get to your data you should you might need to be more targeted in your approach and use the $.ajax() call or one of its variants like $.get() or $.getJSON(). See here

Related

$.ajax() callbacks are not bound to their specific request?

The code is very complex so i have simplified below in order to confirm if the behavior i am experiencing is normal or due so some other error i have made in the code.
I have two separate ajax requests that each have their own unique call back. I do not care which one completes first and one has no dependency on the other
function ajax(url, cbS){
$.ajax({
url: url,
contentType: 'application/json',
dataType: 'json',
success: function(data){
cbS(data)
},
});
}
function callbackSuccess1(data){
$('#div1').html(data)
}
function callbackSuccess2(data){
$('#div2').html(data)
}
//request#1
ajax(myapiurl+'&peram1=100', callbackSuccess1);
//request#2
ajax(myapiurl+'&peram2=200', callbackSuccess2);
The problem: Sometimes callbackSuccess1 gets the data intended for request#2 and vice versa.
It seems that which ever request completes first fires callbackSuccess1 and the second to complete fires callbackSuccess2.
I need the callback to be bound to it's specific request so that regardless of the order in which they complete each request fires it's proper callback.
OTHER INFO: My backed is django-tastypie, at this point i am thinking that tastypie is somehow messing up the response. That is the only logical conclusion, given that the javascript seems to be immutable.
The proof that this is actually occurring is that when i inspect the responce on request#1 the data objects are clearly intended for request#2...
CONCLUSION:
Thanks for confirming that 'each invocation of your ajax() function will create it's own closure'. This was what i thought was going wrong. I found the problem in my API. I was doing some funky stuff and it looks like I had a variable that was not getting trashed in time causing the API to return the wrong data if the first request took longer than the second.
The only issue I see with the code you have included is that the function argument is cbS, but you are calling cbs(data) - note the different capitalization.
Other than that, each invocation of your ajax() function will create it's own closure and have it's own arguments and those arguments will be preserved separately for the internal success callback. This is an important capability in javascript and it works. It does not get the arguments of one call confused with the callback of another as long as you are not using any global variables or state that might change during the execution of the asynchronous ajax call.
You could probably use jsonp and specify callback query parameter in URL for $.ajax
callback would be the name of javascript function which is to be invoked whenever the response is returned from server.
For more details please refer jquery doc : http://api.jquery.com/jQuery.ajax/
For theory : http://en.wikipedia.org/wiki/JSONP
This is mainly used for cross-site ajax calls.

JSONP function call issue

i set up a webservice thats cross domain and needs to be contacted via json with padding
on a simple jquery codeline like this, i am successfull getting back json data.
$.getJSON("http://server/series/hist?jsonp=?", function(data){
console.log(data);
});
the webservice, will wrap the result in a function, whenever "jsonp" exists within in the url.
for those cases i used a default function name like:
myfunction({"a":1})
jquery helps me out here, and trys to call the function, that isnt existing ("myfunction()"). what i am trying to achieve instead is a simple call of the callback function (see above), to handle the data locally.
can you point me in the right direction?
thank you
I'm not quite sure what your problem actually is, but:
Interpretation 1
Assuming that by "locally" you mean "without using a callback":
That is impossible. JSON-P cannot work synchronously as it depends on the addition of a <script> element (which won't be processed until the current function has finished executing).
Interpretation 2
Assuming that by that isnt existing ("myfunction()") you mean "Your webservice always uses the function name myfunction:
Fix the webservice. jsonp=? means "Randomly generate a function name and pass it as the jsonp parameter.
The webservice must use that parameter to determine the function name used, and not use a fixed value such as myfunction.
Interpretation 3
You don't want to use JSON-P as the input, but to call your anonymous function directly.
You can't. It isn't stored anywhere you can access it. You have to rewrite your code so it isn't passed directly to getJSON:
function myFunction(data){
console.log(data);
}
$.getJSON("http://server/series/hist?jsonp=?", myfunction);
myfunction({"a":1})

accessing the data in jquery .when .done function (also is eval that evil?)

I am attempting to do some dynamic loading that includes javascript, css, and html files.
I would like to do it like this:
$.when($.ajax(htmlPath), $.get(cssPath), $.ajax({
url: javascriptPath,
dataType: "text"
}))
.done(function(response){
// i want to pass the data for each of these to the respective functions
appendHtml(what goes here??);
appendCss(what goes here??);
executeJs(what goes here??);
})
.fail(function(){
console.log("failed");
});
So I'm confused on how I separate out the response callbacks. Currently, the response object you see in my .done function is ONLY the HTML file which I called. This function is making the correct ajax calls, and the correct files are all being responded by the server, but how do I access them once ALL the calls are complete? Need this so I won't be applying css/js to HTML which is not there yet, etc. Also, what I do is have the javascript file returned as a string and then i eval() it within the executeJs function. My understanding is that this is an okay use of eval because its the file being returned by our own server so I don't see how it could be tampered with. Is this assumption correct?
Furthermore, in my appendCss function, I'm just adding it to a "style" element in the head. Is there a big issue with this? I am using all this to make a "widget/app based" functionality where I have a js,css,and html for each "app", and I just want to query the server for them when they are needed and the app is loading.
If your downloaded data is being retrieved from the same server as your original web page, then yes, generally, you would have the same level of trust in that code as you do in the code that's already running in the browser.
The problem with eval() in a context like this isn't necessarily that you don't trust the code coming back from your own server; it's that someone might be able to alter the running javascript so that the javascriptPath variable points somewhere you didn't expect it to.
As far as your actual question goes, your done callback will actually be passed three parameters, because your when call included three promises.
Because of the way that you defined your callback (as function(response)), you are only seeing the first one -- the return value from the HTML call. The other two parameters are being ignored.
Each of the three parameters that you are being passed will be an array of three elements: [wasSuccessful, statusText, jqxhr]. To do something useful with them, you could structure your callback something like this:
$.when($.ajax(htmlPath), $.get(cssPath), $.ajax({
url: javascriptPath,
dataType: "text"
}))
.done(function(htmlResponse, cssResponse, jsResponse){
if (htmlResponse[0]) {
appendHtml(htmlResponse[2].responseText);
}
if (cssResponse[0]) {
appendCss(cssResponse[2].responseText);
}
if (jsResponse[0]) {
executeJs(jsResponse[2].responseText);
}
})
(Assuming that you have the appropriate appendHtml, appendCss, and executeJs functions written already)
There are some good examples on this page: http://api.jquery.com/jQuery.when/
And this page has the documentation on the jqxhr object (the third element in each of the arrays that are passed to your done function): http://api.jquery.com/jQuery.ajax/#jqXHR
To access to all the responses just pass three arguments to the done() callback. Try this:
$.when($.ajax(htmlPath), $.get(cssPath), $.ajax({
url: javascriptPath,
dataType: "text"
}))
.done(function(responseHTML, responseCSS, responseJS){
console.log(responseHTML[0]);
console.log(responseCSS[0]);
console.log(responseJS[0]);
})
if you try to print arguments object inside done() you can clearly see that all the responses are passed into the callback
Regarding the use of eval, consider using JSONP instead (dataType: 'jsonp'). This way jQuery takes care of executing the code for you. I suppose jQuery also uses eval() under the hood, but then at least you know that it is done in a proper manner. With respect to safety, also see the related question on when eval() is evil if you haven't already.

send $.post() one at a time ("adding a pause" but really: toggling a 'transmit' flag)

in jQuery, I iterate over an xml list of areas and do a POST request to get detailed information about each area. Because sending thousands of requests at once is debilitating for the client and server, I would like to set a flag so that I wait for a request to finish before sending the subsequent [next] request.
if the xml looks like this:
<area>5717</area>
<area>5287</area>
<area>5376</area>
then the xml parsing kinda looks like:
$(xml).find("area").each( function() {
doPost();
}
and the doPost() function looks like
doPost : function () {
$.post( ... )
}
Basically, I would like to add a toggling "wait" but I'm not sure how to achieve this. Is there a way I can keep the essential ".each" iteration or is another type of loop better for this?
Thanks in advance.
A general algorithm off the top of my head:
You could put the whole list into an array. Take the first item of the array and post it. In the success handler of your post you could recursively call the function with the next index int the list.
I wouldn't use async: false because it would then be a blocking operation, which I assume the OP doesn't want.
You can use:
$.ajaxSetup({async:false});
at the top of your script to make your AJAX calls synchronous.
Alternately, you can replace $.post() with $.ajax() and set the async flag to false.
can you do a setTimeout ? that will allow for the function to still process asynchronous and allow for you to wait for some time in there too.
http://www.w3schools.com/js/js_timing.asp
setTimeout(function() {}, 5000)
You can refactor your doPost() function to take the <area> element to process as an argument, and chain into the next element from your success callback. Something like:
(function doPost($area) {
if ($area.length > 0) {
$.post({
// your options,
success: function() {
// your success handling...
doPost($area.next("area"));
}
});
}
})($(xml).find("area").first());
EDIT: Maybe the code above was a little too compact indeed.
Basically, the aim is to refactor your function so that it takes a jQuery object containing the next <area> element to process, or nothing if processing should stop:
function doPost($area) {
if ($area.length > 0) {
// Perform POST request and call ourselves from success callback
// with next <area> element (or nothing if there's no such element).
}
}
Then call this function with the first <area> element to process:
doPost($(xml).find("area").first());
The first code fragment in my answer does both at the same time. Functions are first-class objects in Javascript, and you can call a function you've just defined by enclosing its definition with parenthesis and providing the usual argument list, also surrounded by parenthesis.

Can I use a static (i.e., predetermined) callback function name when requesting JSONP with jQuery?

The jQuery documentation lists the following example of using $.getJSON to request JSONP:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 3) return false;
});
});
Rather than use this method, which generates a dynamic callback function name because of this parameter:
jsoncallback=?
I want to be able to set that in advance to a hardcoded function name, like this:
jsoncallback=test
This works, in the sense that I run the script and the JSONP that I get back has the JSON object wrapped in a call to test().
However, I can't figure out how to set up the callback function. Shouldn't it be as simple as this?
function test(data) {
console.log(data);
}
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=test");
When I try that, I get back the JSONP which is wrapped in test(), but the function test() that I've defined is never called. Am I missing something?
Thanks for any help!
As defined in the documentation for you to use the following method
jQuery.getJSON(...)
you need to specify callback=? when making a JSONP call. I usually only uses this for response types of "json". For response types of "jsonp", you want to use:
jQuery.get(...)
and specify the type as "jsonp". See this documentation on the subject. But that is also bound by the fact of having to have a callback=?.
What I think you are looking for is this:
jQuery.getScript(...)
Which should execute whatever method you have defined in your callback.
Ah, the "Related" sidebar section saved me here. After I submitted this question, I found a similar one already asked:
using a named function as the callback for $.getJSON in jQuery to satisfy Facebook request signing demands
Duncan's answer from Oct. 15 solved this for me:
window.fixed_callback = function(data){
alert(data.title);
};
$(function() {
$.getScript("http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&tagmode=any&format=json&jsoncallback=fixed_callback", function(data) {
alert('done'); } );
});
I guess the key is using $.getScript instead of $.getJSON. One can still specify an anonymous callback function in the parameters of the $.getScript method, which will be executed after the callback function named in the request URL parameters ("fixed_callback" in this case). Hope this helps someone down the road.

Categories