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
});
Related
It is not mentioned in the docs, but apparently if the local AJAX success handler throws an error, even the global ajaxSuccess handler is not invoked. Is there a way around this mechanism cause if you want to distribute a JS library or util function that does something on ajaxSuccess, you can't necessarily have control over the success handler and make sure it does not raise an exception.
$(document).ajaxSuccess(function(ev, jqXHR, settings) {
console.log('ajaxSuccess called!'); // does not get called
});
$.ajax({
'url': '/',
'type': 'GET',
'success': function (response) {
console.log('success called!');
throw new Error();
}
});
CodePen: http://codepen.io/anon/pen/Ldybr
Here is the documentation that partially explains the issue you're facing:
Events
...
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
ajaxSuccess (Global Event)
This event is also only called if the request was successful.
error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event)
This global event behaves the same as the local error event.
This is the normal flow of events, i.e. any global event is called after local. But in case any callback throws exception, no other callback is called, because jQuery internally doesn't wrap the callback in try-catch (you may do this locally in your callback though).
Another solution, as I've mentioned in comments, is dataFilter property of ajax options, which allows you to perform needed actions before any local callback (success or error) is called. Here is demo from my comments to the question, just in case:
$.ajaxSetup({
dataFilter: function(data, type) {
console.log('dataFilter called!');
return data;
}
});
I'm having trouble with events in a MooTools Form.Request():
new Form.Request(e.getParent('form'), $('update'), {
resetForm: false,
onRequest: function () {
loading(e)
},
onSuccess: function () {
toggle(e)
}
}).send();
The onSuccess event triggers happy, but the onRequest event does nothing. Am I overlooking something?
The name of the event is send not request. So you are looking for onSend:.
Have a closer look at the documentation:
Events:
send - (function) The function to execute when the request is sent. Passed the form being submitted and the data (an object) being submitted.
failure - (function) The function to execute when the request fails. Passed the XHR that is returned by Request on failure.
success - (function) The function to execute when the request succeeds. Passed the target being updated, the request text, and the request xml.
I have a application where there are numerous number of ajax calls to the server.
Now I want to audit the response that comes from the server (This requirement poped up after the ajax code was laid).
So I have a function that would audit the response data, only problem is how can I get the data to be sent to the function which now sits separately.
I don't want to do the laborious work of adding the line of code for calling the function in each ajax call.
Is there easier and general way out. Somehow I could detect when a response come back and then process the response.
Using both traditional javascript method as well as jquery ajax calls in the system. (The app has been getting changes from a long time and has changed hands a lot so the new things get added and the older ones never get removed)
Wrap your ajax calls with a helper function and use it throughout your code.
An (untested) example:
MyApp = MyApp || {
logRequest: function _logRequest(settings, response) {
// Log your response
},
ajax: function _ajax (settings) {
var that = this;
// Log attempt request here?
// Example of logging the success callback (do similar for error or complete)
if (settings.success) {
// A success handler is already specified
settings.success = function (data) {
that.logRequest(settings, data); // Log the response
settings.success(data); // Call the original complete handler
};
} else {
// No success handler is specified
settings.success = function (data) {
that.logRequest(settings, data);
};
}
return jQuery.ajax(settings);
}
};
I favour this mechanism for lots situations where I want to reduce boilerplate. I only have to modify the state of the MyApp object which is my own (named appropriately for the application), so it is sort of an interface that allows you to intercept function calls without modifying other global objects. You can also swap this functionality out with something else very easily without having to update your references everywhere, which could be useful in a lot of other situations as well.
Using .ajaxComplete() should be enough to catch the onComplete event for all AJAX requests made through jQuery. Isn´t that what you´re asking for?
$('.ajaxRequest').click(function(event) {
event.preventDefault();
$.getJSON(
'/echo/json/',
this.id,
function(data, textStatus, jqXHR) {
console.log(data, textStatus, jqXHR);
}
);
});
// Listen to all ajax requests
$("#log").ajaxComplete(function(event, request, settings) {
console.log(event, request, settings);
});
View demo.
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.
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/