so we have this ajax option beforeSend
$.ajax({
beforeSend: function(){
// to do
}
});
is there a way to override this globally?
for example, i want to insert a function on all ajax and I want to do this by creating a single function rather than going all $.ajax calls one by one.
You can check the .ajaxStart() - it's global for all AJAX calls.
Whenever an Ajax request is about to be sent, jQuery checks whether
there are any other outstanding Ajax requests. If none are in
progress, jQuery triggers the ajaxStart event. Any and all handlers
that have been registered with the .ajaxStart() method are executed at
this time.
More info # https://api.jquery.com/ajaxStart/
Related
Hi I am running an AJAX Post to my PHP url and when done I am returning a document.ready function with my appended jQuery page.
I want to make sure if I am doing this correctly when placing the function in the success part of my AJAX post. It will not work at the minute. Any help would be great?
function loadJobRequests() {
/ /AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/json-data-
jobrequests.php",
data: { userEmail: localStorage.getItem("email") },
cache: false,
success: function() {
$(document).ready(function(){
I just need to find out if i have to pass any parameters into the function at success and then same same parameter into document.ready. Thanks
Short answer: no, you shouldn't use $(document).ready(...) here. The function you put inside that is only executed at the moment the DOM is first "readied", shortly after page load - this will be long since past by the time your script has been loaded, executed, fired an Ajax call and then returned the response (all of which needs to happen before your success callback happens).
But the very reason that $(document).ready(...) doesn't work also means that you don't need it here. The only reason it's used is to make sure that any DOM elements you refer to (typically to attach event handlers to) actually exist and the point this code is executed. Since the "ready" event has long since fired by the time the Ajax response comes in, the DOM will accurately reflect the current content of the page, and you can safely do whatever you want to manipulate it.
So whatever function you were going to put inside there, just put directly in the success callback.
If there is jquery ajax loading and I fire another ajax by quickly clicking the button, it kind of gets stuck. How can I handle multiple requests fired together?
How do I do following?
Discard/abort all previous requests and only process the latest one.
Do not allow new request until previous request completes (variation: can be same ajax request or any new ajax request from the page).
AJAX is Asynchronous. So you can fire them at the same time.
Or in the success callback (or .done() callback), you can call one request after another. So it will be easy to manage your issue (you click the button but get stucked), because you can control.
$.ajax({
url: "http://..."
})
.done(function( data ) {
// Other AJAX call
// or restore disabled elements
// while you were receiving the response.
});
If you want a work-around, just tell me.
you can use ajax "beforeSend" to lock the current request.So that user can send a new request only if the previous one is done. As for the process sequence, you can use a global value to store data and always assign it with the new response value.
function request(callback){
if(!$btn.hasClass('disabled')){
$.ajax({
type:'...',
url:'...',
beforeSend:function(){
$btn.addClass('disabled');//so that user cannot send a new request
},
success:function(data){
window.g_data = data;
callback && callback()//success callback
$btn.removeClass('disabled');
}
})
}
}
function callback(){
//process window.g_data
}
Have a look at this library:
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
Async
I'm having numerous AJAX call using JQuery. Among these is an AJAX call, let's say auth() that checks whether the user is currently logged to the system, idle, etc, and if not, will cause the page to redirect to the login page.
This auth() function is called every minute. Other than that usage, I want to call this function on before every other AJAX call that will be made— just to ensure that they are logged to perform a transaction.
I'm thinking of using the beforeSend property of $.ajaxSetup to achieve this, but won't it also be attached to auth() since it is also an AJAX call? I can confirmed this because I have tried using beforeSend and it throws an error:
RangeError: Maximum call stack size exceeded
How can I select all AJAX call (except for auth()) and attach it an "onBeforeCall" listener?
You could overload the ajax method of jQuery:
var $ajax = $.ajax; // save old ajax method
$.ajax = function () {
if (!auth())
throw 'NOT AUTHENTIFICATED!'; // or whatever
return $ajax.apply(this, arguments); // if auth() passed call the old ajax method and return it so the whole jQuery API works...
);
The best way to do is to write a generic function which will act as a proxy to all of your AJAX calls. Something like this:
var ajax = {
send: function(url,type,success,error,data){
$.ajax{
url:url,
method:type,
beforeSend: function(xhr, opts){
if(!auth()) {
xhr.abort();
}
}
success:success,
error:error
}
}
}
Call all of your AJAX calls this way:
ajax.send(url,type,success,error,data); //Pass success and error as functions
Using jQuery (v2.1.4), is there any difference between these two methods?
1) $.ajaxSetup(beforeSend)
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
}
});
2) $(document).ajaxSend
$(document).ajaxSend(function (event, jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
});
Is there any reason to prefer one over the other?
Thanks!
From jQuery $.ajaxSetup() documentation:
All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().
The $.ajaxSetup() does something like this:
ajaxExtend(jQuery.ajaxSettings, target);
From $.ajaxSend() documentation:
Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.
And the jQuery source for $.ajaxSend():
function (fn) {
return this.on(type, fn);
}
So, basically the $(document).ajaxSend() adds an event listener to all the document where you can make any handler to execute anytime a jQuery Ajax call is about to be sent (the handler intercepts it, but XMLHttpRequest.readyState value is already 1 - "Opened").
This means that if $.ajax() is called with the global option set to false, the ajaxSend() method will not fire.
While on the $.ajaxSetup() you are in fact creating defaults for every single jQuery Ajax call's settings, and the callback defined through the beforeSend option will always be called (XMLHttpRequest.readyState value is 0 - "Unsent").
From JQuery's documentation:
There are two types of events:
Local Events
These are callbacks that you can subscribe to within the Ajax request
object, like so:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
Global Events
These events are triggered on the document, calling any handlers which
may be listening. You can listen for these events like so:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
Global events can be disabled for a particular Ajax request by passing in the global option, like so:
$.ajax({
url: "test.html",
global: false,
// ...
});
for more information
Both do very similar function , but it always depend on the need
There are some key points , on which you may focus
ajaxSend() method, must be attached to document only.
if $.ajax() is called with the global option set to false, the ajaxSend() method will not fire.
the beforeSend option will be called regardless of the type of request.
From the perspective of priority, you can use in such a manner, do all setup options in ajaxSend and for custom or specific ajax request override it with beforeSend in $.ajax().
HTML
<body>
<div><h2>Let AJAX change this text</h2></div>
<button id="btn1">Change Content</button>
<button id="btn2">Change Content Override</button>
</body>
JS
$(document).ajaxSend(function(e, xhr, opt){
$("div").append("<p>Requesting " + opt.url + "</p>");
});
$("#btn1").click(function(){
$("div").load("yourpage.html");
});
$("#btn2").click(function(){
$.ajax({
global: false,
beforeSend:function(){$("div").append("<p>Overriding</p>");}
});
$("div").load("yourpage.html");
});
LIVE http://jsfiddle.net/mailmerohit5/w8t44247/
I several HTML elements that initiate ajax when clicked. How can I check which element was clicked inside the ajaxComplete event?
I tried event.target but it returns the entire document.
$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url.indexOf("somelink/hello") > -1) {
console.log("return here element that initiated ajax")
}
});
Note: The tricky part - I don't have access to the ajax request that is sent on click. I can't configure the code that makes the request. I can only check when the ajax is complete.
I first need to run the ajaxComplete event then check which element initiated ajax because I need to add some html to that element. For this reason I'm trying to check in the ajaxComplete event.
The $.ajaxComplete() handler is not an object-specific handler; you attach it to the document to be notified whenever any AJAX request completes. From the jQuery docs:
If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request.
So, since settings is a plain Object, you can extend it with a property that will then be passed to the handler, as you can see below with requestingObjectId. DEMO
var onComplete = function(event, jqXHR, ajaxOptions) {
alert("Requested with " + ajaxOptions.requestingObjectId);
};
var makeRequest = function() {
var id = $(this).attr('id');
$.ajax({
url: '/path/to/server',
data: { foo: 1 },
requestingObjectId: id
});
};
$('button').click(makeRequest);
$(document).ajaxComplete(onComplete);
Best and easiest way is to store the element in a global variable when you send the ajax call. Set it to the event.target.activeElement. Then in your ajaxComplete you can just access that var to change CSS etc.
Upon further consideration, if you use my solution you would have to limit it to one ajax request at a time. Otherwise a new ajax request would overwrite variable if the initial ajax request hadn't completed yet. I'd take Palpatime's answer.
An jQuery AjaxRequests is NOT send by an control itself. It is send by the code that the developer wrotes as event function onto this Dom element.
Means the best thing you can get is the callee of $.ajax() by overwriting and wrapping it. And only if the callee is not written in strict mode.
I would prefer to read the documentation of that framework who is building your controls or if it is built by another company/guy contact them.
As the element is not the direct caller of the $.ajax, I see no other way.