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);
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!
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.
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 am trying to override the jQuery ajax function to handle a default action on a success event but also executing the callback function that i am using in the options parameter.
What the purpose is there is tags returning in the response that I always want to strip out of the response for use elsewhere.
The scenario is:
Ajax submit
Ajax Success
--DEFAULT SUCCESS ACTION
--Call Ajax Success Callback
Can anyone help?
I have tried extending
jQuery.ajax
jQuery.ajaxSuccess
jQuery.ajax.done
The code I have is:
var _ajaxSuccess = jQuery.fn.ajaxSuccess;
$.fn.extend({
ajaxSuccess: function (a)
{
_ajaxSuccess.apply(this, a);
}
});
There is the global ajaxSuccess callback:
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
That will let you call your own function on every successful AJAX call without interfering with the usual success callbacks.
There are various other global AJAX event handlers that you might want to look at too.
If those callbacks don't have the right timing or capabilities for you, then you could write your own wrapper for $.ajax and use that:
function wrapped_ajax(options) {
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
// Do whatever needs to be done here.
if(success)
success(data, textStatus, jqXHR);
};
return $.ajax(options);
}
You can do whatever you need to the usual success callback parameters before calling the original success callback. You'd call wrapped_ajax in exactly the same way as $.ajax. You could use the same technique to hook into the other callbacks as well.
try jQuery.ajaxSetup it may help you ,read about it here
Do like this:
$.ajaxSuccess(function(){
//somethingtodo
});
Mentioned in http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/ heading twelve.
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.