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.
Related
I ask a friend and ask what is (data, function(i,e) in this code and he said this is callback then i search the internet about callback and doesn't understand it. I read about this What are callback methods?what is callback in simpliest way ?
$.each(data, function(i,e){
console.log(e.id);
});
What is the use of (data, function(i,e) here?
$.ajax({
type: "GET",
url: pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle,
dataType: "jsonp",
jsonpCallback: 'callback',
contentType: "application/javascript",
success: function(data) {
console.log(data);
}
});
A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.
*Here's a little something for you to understand callbacks better:
Guy 1 to Guy 2: hey dude I wanna do something when a user clicks in there, call me back when that happens alright?
Guy 2 calls back Guy 1 when a user clicks here.*
A callback method which is called back.
Who calls it back at you ?
Your framework calls it back.
Why it calls it back ?
Because you ask for it to get called back because you want to do some processing when something happens.
Examples
You are doing some processing and don't know when it completes. You provide a callback , and you continue with some other work. Your call-back function will be called back to tell you that processing is finished and you can do something at your end now.
You want to know when some control fires some event so that you can do some processing. You provide a call-back function as event handler.
You are not happy with default processing done by framework and want to override that processing, you provide a call-back and framework calls it back to use your own processing.
So, in general : You ask a component/framework to call your provided method. You never call that provided method from your code, someone else calls it back.
A callback function is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the another Function.
Like this
(data, function(i,e)
We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition.
Note that the callback function is not executed immediately. It is “called back” at some specified point inside the containing function’s body. For more info Refer Here
Normally, JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is finished.
For e.g, this is a call back function:
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
In this case the function hide will be executed before that alert which is precisely what we want.
On the other hand if you don't use call back function say this way:
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
In this case alert will be executed even before the function hide is executed. This is the typical use of callback function in Javascript.
I have this function when I am doing a request for an image in javascript
xhr.onload = function(e) {
console.log(e);
};
this works as intended, but when I try and do something like this in jQuery
success: function (data) {
console.log("hi");
}
nothing gets printed. I inspect the request using the developer chrome window and the request works fine but for some reason is not calling the function within the success clause. Is there any way that I can make that function be called regardless of how the request executes? Like onLoad.
Thanks!
You want complete, as it executes regardless of the response status:
complete: function (data) {
console.log("hi");
}
complete
[...]
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Another alternative -
$(document).ready(function(){
//Write code here
});
It's probably obvious to you, but I can't figure it out.
I need to make function that returns it's inner-function's value. In other words, I have function get_users() that must return JSON object. That JSON object is got by $.post (built-in jQuery).
function get_users() {
return
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
return response;
},
'json'
);
}
(above is what I tried to do, but it returned undefined - what a surprise)
Because of variable scope, I cannot just make variable in inner-function because it won't be visible in main function. I don't want to use global variables neither. Looking for better solution!
Thanks in any advice!
Why are you fighting against the asynchronous nature of AJAX? When you do AJAX you should get accustomed to work with events and callbacks instead of writing sequential code. You can't return the inner contents. The simple reason for this is that this inner function could execute much later than the outer function. So the outer function will return a result much before the success callback executes.
So here's the correct way:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// instead of trying to return anything here
// simply do something with the response
// Depending on what the server sent you there
// will be different ways.
// Here you could also call some other custom function
// and pass it the response
}
'json'
);
}
You can't return values from ajax calls. (Without setting async false, but that wouldn't really be ajax)
By the time you hit the inner return, the outer function has already completed
You will need to use a callback to process the users.
get_users(function(response) { // this anonymous function is passed in as a parameter
// do something with the response
});
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// call the passed in function and pass in the response as a parameter
callback(response);
},
json'
);
}
You need a primer on how asynchronous ajax calls work.
When you call $.post(), it starts a networking call to do the post and immediately returns from the $.post() call and continues executing the rest of your javascript. It will even exit your function get_users() right away.
But, the ajax call is not yet done - it's still in progress. Some time later, the ajax call will finish and when that happens the success handler for the ajax call that you have defined as function(response) {...} will get called. Only then, at that later time, is the response value from the ajax call known.
This is what asynchronous ajax means. You cannot write a call like get_users() and expect it to get the users and return with them. Instead, you have to make use of callback functions that will get called some time later (when the ajax has completed) and you can continue the path of your code then. Yes, this is inconvenient, but it's how things work in javascript with asynchronous ajax calls. The benefit of asynchronous ajax calls is that the browser and other javascript code can be fully live while the ajax call is underway. The cost of asynchronous ajax calls is that coding for them is more complicated.
You have a number of choices for how to deal with this complication. First off, you can make your get_users() call and then just continue the programming sequence that you want to carry out in the internal callback inside of get_users() since that's the only place that the response (the actual users) is known. If you're only using get_users() in one place in your code, then that could work fine. It would look like this:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
},
'json'
);
}
If you need to use get_users() in several different places for different purposes, then you can change it to take a callback itself and let the post call just call that callback when the ajax call is done. You would then complete your processing of the response in that callback function:
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
callback,
'json'
);
}
In this second option you could call get_users() like this:
get_users(function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
});
There are even more advanced options available using jQuery's deferred object.
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);
I have written a function that retrieves a html template, then binds data using jQuery.tmpl. I think it's fairly neat and tidy and encapsulates what I need and provides me a reusable function. My question however is can it be improved.
My main concern is what if the $.get method fails, and also how the callBack function is executed.
function Bind(templateURL, templateData, templateTarget, callBack){
var req = $.get(templateURL);
req.success(function(templateHtml) {
$(templateTarget).html(''); //clear
$(templateHtml).tmpl(templateData).appendTo(templateTarget); //add deal
callBack();
});
}
You can pass the result of tmpl() directly to html() to clear your target container and append the new content at the same time. You can also chain the result of $.get() into your success handler to avoid using a local variable:
function Bind(templateURL, templateData, templateTarget, callBack)
{
$.get(templateURL).success(function(templateHtml) {
$(templateTarget).html($(templateHtml).tmpl(templateData));
callBack();
});
}
If $.get() fails, nothing will happen since you do not register an error handler. What that handler would do is up to you, but you might want to display an appropriate message in an alert box or somewhere on the page.
Your second concern is less clear. As it stands, callBack will only be called on success, and without arguments.
You can use $.ajax to assign and error calback. ex:
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
Check the api http://api.jquery.com/jQuery.ajax/