I'm having this simple get request:
$.get('ri/i18n/locale')
.done(function() {
console.log(this);
})
.fail(function() {
console.log(this);
})
.always(function(){
console.log(this);
});
Unfortunately none of the handlers are ever called.
I cann confirm that calling ri/i18n/locale in the browser returns a valid JSON string. I'm using jQuery 1.11.1 .
Any ideas what's wrong?
Your issue might be what version of jQuery you are using. Before jQuery 1.5, a jqXHR object was not returned with a $.get(), which is what allows you to use the promise behavior. The relevant jQuery documentation.
After all I just missed the asynchronous nature of the ajax call. I had a breakpoint on all console.log statements and the statement following the ajax call. Since the the statement after the ajax call was hit first I assumed none of the console.log statements gets called.
Since I need the result of the ajax call to go on, I have to move all my code into the done() function.
Related
Recently I abstracted a bunch of AJAX calls into a function using the $.post() method. My idea was to use the jqXHR object returned by $.post() to add standard error handlers and such (via .fail() .done() .always()) to remove code duplication. I then thought that I could return the jqXHR object from the method to the original calling function so I could add additional handlers to do more context-specific things.
However, the jqXHR object returned seems to be a copy of the original object, not the object itself. As such, its state never gets updated by the original call so none of my additional .done() functions get executed.
Is it possible to return a reference to an object in JS? I have a C++ background, so is there a way to mimic the "return pointer to object" functionality in JS?
I know there have been discussions on pass-by-reference/value on here, but I couldn't find one dealing specifically with Deferred objects
EDIT: example code
function AJAX(url,data,onSuccess) {
var jqxhr = $.post({url,data});
jqxhr.done(onSuccess);
jqxhr.fail(displayError());
return jqxhr;
}
...
function example() {
var dfrd = AJAX("example.php",data,successFunc);
dfrd.done(alert("Hello, World!"));
}
The .done() & .fail() within the AJAX function get executed normally, but the .done() within example() never executes because dfrd.state() is always pending
So this turned out to be a timing issue.
It appears that, with multiple .done() functions, there is a slight delay when the function receives a response from the $.post() call. So my onSuccess(resp) {} that was passed to the AJAX function would execute after the alert(). The particular onSuccess function I was using to test had a page refresh call in it, which would close the alert before I could see it.
I have a C++ background, so I guess I need to upgrade my JS testing procedures.
Thanks to all who commented!
Okay so look at these to alert()s. Here is the full code:
function OfficialFacebookLikes(Title)
{
$.getJSON('https://graph.facebook.com/'+Title, function(data) {
alert(data['likes'].toString()); //<<temp
return data['likes'].toString();
});
}
$(document).ready(function(){
$('.ui-btn').click(function(){ //cocacola
var LikeCount = OfficialFacebookLikes("cocacola");
alert(LikeCount);
});
});
Why does
alert(LikeCount)
display (which is "undefined" when displayed) before
alert(data['likes'].toString())
I called the function OfficialFacebookLikes before I called the alert(LikeCount). Could someone please explain why this is occurring. If my thought process isn't making since.. I'm use to coding in C++.
This is an asynchronous Ajax call. You won't have data available until the call returns. In your document ready code, you are attempting to alert the call immediately.
Instead, do whatever you need to do with the result set in the callback handler of the ajax:
$.getJSON('https://graph.facebook.com/'+Title, function(data) {
doSomethingWithMy(data);
});
The .getJSON function is asynchronous, this means that it needs a callback to call when it's finished, otherwise you'll never know when the function has been completed. Asynchronous functions run separately from the rest of the code.
When you call OfficialFacebookLikes("cocacola") it will call the .getJSON function. Now the .getJSON functions starts by its own and doesn't stop the script, so right after calling OfficialFacebookLikes("cocacola"), the next line of code is executed, which is actually alert(LikeCount). But LikeCount has not yet been defined, since that .getJSON is still working.
When .getJSON finishes working the callback function given in $.getJSON(..., function() {... }) gets executed, and then the LikeCount variable gets defined. So if you want to alert LikeCount you have to put the alert() inside the callback of .getJSON.
I am using jquery for ajax calls
All the calls are called immmediately on page load and we are getting the responses at almost the same time.
the issue is, the 3 calls are fired and I am getting the data, but the callback function is fired for the first call only.
the other two callbacks are not called, the callback is defined as a separate function,
If I just write an alert instead of calling the callback method, all the 3 alert message are coming
So the issue is when we write the callback method, do any one have any idea of the strange behaviour?
We tried to reorder the calls, the behaviour is similar, which ever is called first, its callback will be called, for the rest, it will not be called
var url = "/test1";
ajaxCall(url, testMethod1, false);
var url = "test2";
ajaxCall(url, testMethod2, false);
var url = "test3";
ajaxCall(url, testMethod3, false);
testMethod1:function(data){
console.log("first"+data);
},
testMethod2:function(data){
console.log("second"+data);
},
testMethod3:function(data){
console.log("thrid"+data);
}
ajaxCall is defined as jquery ajax, the issue is only the testMethod1 is called, the rest 2 are not called
Regards
Hari
Well the thing that immediately caught my eye is that the URL for test1 has a forward slash preceding test1. This means that you are using a valid link in only test1. The alerts will trigger because you are probably not trying to access the data returned (which would still work even though the ajax request fails), where as you are trying to access the data in the coded call back functions you have provided, which will obviously throw a NullPointerException or whatever the equivalent as the ajax call fails due to an incorrect URL. Therefore data never gets set and the code doesn't work.
so I've been messing around with some Jquery Ajax promises/deffers etc... and i've come across something I don't completely understand, not strictly related to the Jquery Ajax.
I have always declared and called functions like so:
function foo1() { //sets function
alert('foo1');
}
foo1(); //calls function
But it seems the more I see different code a lot of people are declaring functions like the following, I just copied and pasted an example I saw so I would't miss anything:
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(myStopAnimationFunction);
I understand what the above does, just an example.
The question is, is it better to assign functions to variables? What are the pros/cons, and in what situations is this way used?
At what point in this code is the actual function called. Does
promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Thanks
In your example, you're assigning your promise variable to what $.ajax returns (which is a jqXHR object)
var promise = $.ajax({
url: "/myServerScript"
});
Your then saying that once it's done, you want to call myStopAnimationFunction. Because $.ajax is async by default, the browser will skip right over this and only call your myStopAnimationFunction when the request is complete.
promise.done(myStopAnimationFunction);
Now, with your myStopAnimationFunction; you could always just do the following:
promise.done(function(){
$('.loader').hide();
});
but if you have code which you'll be using a lot, put it in a function so you don't need to repeat yourself (see DRY) - this has nothing to do with jQuery, however.
Your example is exactly the same as doing:
$.ajax({
url: "/myServerScript"
}).done(function(){
$('.loader').hide();
});
Those are two very different things! The first one is a function declaration. The second one is a function invocation, and what is assigned to the promise variable is the value returned by the function you're calling ($.ajax).
In any case, it is possible to assign functions to variables too (but I'm not sure if that's what you're really asking – if it is, this is a duplicate of var functionName = function() {} vs function functionName() {}).
Does promise.done(myStopAnimationFunction);
call both the ajax function, and then the callback, or just the callback?
Neither. That line is a call to done on the promise object, to register a callback to be called when the ajax response arrives. At that point you call done, the ajax request may have already fired, and the response even might already be available (if that's the case, the callback will be called immediately).
i would like to know if is possible to generate a method/extension/change for the jQuery lib to specify for all $.ajax() calls a method to be executed for example in timeout:, or in beforeSend:, statments
Of course. There are many ways, but one of the simple methods for having a centralized method to be run on every ajax call, is to wrap jQuery ajax in your custom ajax wrapper.
(function ($){
$.customAjax = function(path, data, successCallback, errorCallback){
function errorFallback(){
// Here, do what you want to do on any ajax call, which doesn't have error callback
};
errorCallback= errorCallback|| errorFallback;
$.ajax({
// Calling the jQuery ajax, passing either specified error callback or a default callback.
});
};
})(jQuery);