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.
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 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
});
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'm testing a Backbone.js app using Jasmine and Sinon. I'm trying to verify that clicking a button click calls the Model's save() method and processes the success callback which adds a message to the view's el element. I'm having trouble getting the sinon server to trigger the Model's success callback.
Heres what my spec's beforeEach looks like (the variables in beforeEach are all is var scoped in the describe function).
beforeEach(function(){
server = sinon.fakeServer.create(); //create the fake server
server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"]); //fake a 200 response
loadFixtures('signup_modal.html'); //load the fixture
element = $("#signupModal");
specSignUp = new SignUp();
signUpView = new SignUpView({model : specSignUp, el: $("#signupModal")});
});
And this is what the actual test looks like:
it("Should call send request",function(){
element.find("#signupButton").trigger('click'); //click the button which should trigger save
server.respond(); //fake the response which should trigger the callback
expect(element).toContain("#message");
});
While trying to build the implementation of this I created a simple callback method to show me that the success callback is beign triggered:
sendRequest: function(){
console.log("saving");
this.model.save(this.model.toJSON(),{success: function(data){
console.log("success");
iris.addMessage(this.$("#messageContainer"),"Thank you");
}});
}
When I run the test the console shows "saving" but the success callback isn't getting called.
Backbone expects the response text to be valid JSON and was bombing out because of the response "OK" in the server.respondWith() method.
Changing the method to:
server.respondWith([200, {"Content-Type":"text/html","Content-Length":2}, '{"OK":"True"}']);
The success callback was being processed successfully.
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.