My question is probably nooby but I really cannot find an answer actually.
I want to use abort() method on a specific ajax. However i always use request=$.ajax...for all my requests and the request.abort() cancell ALL my ajax, intead of only the one i want.
Is there a way to point on the right one by naming it or something?
here is my code
request.abort();
request = $.ajax({
url: "getphp/gettooltip.php",
type: "GET",
data: {db : db, id : url.substring(url.lastIndexOf('=')+1)},
dataType: "JSON"
});
request.done(function(msg){
d3lttFillInTooltip(msg,db)
$('#d3ltttooltipdiv').css('visibility','visible');
});
I absolutely need to cancel the last call of this same ajax before running this one.
Any help would be welcome :)
You need to change your code so that you are not simply assigning request=$.ajax({...}); for every single call. You need some sort of list or mapping of requests. How you implement this depends on when you need to abort requests. For example, if you just wanted to have a stack of requests, so that you could easily abort the last request, you could do something like this:
var requests = [];
requests.push($.ajax({
// request 1
...
}));
requests.push($.ajax({
// request 2
...
}));
requests.push($.ajax({
// request 3
...
}));
requests.pop().abort(); //aborts request 3
// or...
requests.shift().abort(); //aborts request 1
If this doesn't help you, please provide more info on when you need to abort requests. Bottom line -- don't set request to every single ajax request you make if you want to be able to target specific requests.
Use a different variable for each jqXHR object.
Related
I know we can make a javascript ajax request from some server and it either receives the response or gives timeout error after some time.
Let's consider this scenario when we don't want to wait for the request rather the server would send a response(or we can say it would be another request from server to client) async at any time after getting the request and then call a javascript CB function with the response.
I am looking for ideas for how to go about it mainly supporting all modern browsers and if possible not relying on any 3rd party plugin except may be jQuery.
The main feature of Ajax is that it IS asynchronous by default, and your program will continue to run without waiting for the response. So unless I'm misreading your question, it is what you need.
If you use jquery, then you pass in a callback function that will execute only when the server sends back a response. You can specify a timeout in the settings, though I'm not sure what the maximum time you can provide without getting a timeout error. But it will be several seconds, at least.
You can even specify different callbacks for success and fail as follows (adapted from the jquery ajax API, but added a timeout of 5 seconds):
var request = $.ajax({
url: "http://www.some.url/",
method: "GET",
data: { some : stuff },
dataType: "html",
timeout: 5000
});
request.done(function( data ) {
console.log( "SUCCESS: " + data );
});
request.fail(function() {
console.log( "Request failed");
});
I came across this question after 4 years. I dont remember in what context I asked this but for anyone who has the same query:
Http is a request/response protocol. Which means the client sends a request and the server responds to that request with some message/data. Thats the end of the story for that request.
In order for the server to trigger something on the clientside we will have to use something that keeps the connection to the server rather than ending the communication after getting the response. Socket.io is bi directional event driven library that solves this problem.
To update a cart (PHP Session storage and reserve the stock of items in database) on my online shop, I simply add a timeout of 100ms after calling it and remove Success/Error callback.
$.ajax({
url: 'http://www.some.url/',
method: 'GET',
data: {
some : 'stuff'
},
dataType: 'html',
timeout: 100
});
Note : It doesn't matter if some requests didn't arrive, because when the order is saved, an update of the whole cart is sent with a callback.
If your query needs acknowledge, don't use that solution !
I believe your question is similar to this
by Paul Tomblin. I use the answer provided by gdoron, which is also marked as the best solution, and also the comment by AS7K.
$.ajax({
url: "theURL",
data: theData
});
NB: No async parameter provided.
While learning through ajax in jQuery, I came across 2 terms, viz., $.ajaxPrefilter() and $.ajaxSetup(). All I can find out is that these make some changes in AJAX before loading or making call to $.ajax().
Can someone simplify and explain these terms in easiest form along with a slight comparison of the two?
$.ajaxSetup() - Set default values for future Ajax requests. You could, for example, set the ajax URL that you always want to use for every request here.
Example:
$.ajaxSetup({
// Always use this URL for every request
url: "http://example.com/ajax.php"
});
$.ajaxPrefilter() - Modify existing options before each request is sent. You could, for example, append a query string component to every ajax request that is sent out.
Example:
$.ajaxPrefilter( function(options) {
// Always add "?debug=1" to every URL
options.url += (options.url.indexOf("?") < 0 ? : "?" : "&") + "debug=1";
});
$.ajaxSetup simply takes an options object, and uses it as the defaults for future $.ajax() calls (and other calls that are shortcuts for this, like $.get). For instance,
$.ajaxSetup( { dataType: 'json' });
makes this the default dataType for future calls.
$.ajaxPrefilter lets you run a custom function before sending each AJAX request to the server. It can examine the options to that call, and then change them in any way that it wants. So it provides much more flexibility and control than $.ajaxSetup.
How can I make sure that a piece of code has executed completely before executing another? I am sending some ajax requests to a server and then using the returned data to generate the rest of the webpage. the things is, is that i need to have all that data in the webpage to proceed with the rest of the code as that code will affect what has been generated and, that code, runs before the json requests and all of that have finished... is there any way I can make sure this does not happen? I managed to solve it by performing the requests and then asking the user to press a button but that is a total no-sense way of doing it.
Any ideas?
Here is some code: The problem is that the second line is executed before the first (there are many calls to similar JSON functions).
$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();
Unforunately I cannot use the ajax synchronous property because: "dataType: "jsonp" requests do not support synchronous operations"
If you are using jQuery 1.5+ you can make use of deferreds to solve your issue:
function first_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_1
);
}
function second_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_2
);
}
function final_sucess_callback() {
// Do all your display work.
}
jQuery.when(first_ajax_request(),
second_ajax_request()).then(final_success_callback);
There is an excellent article on the topic that you should read up on as well by Eric Hynds. He gives some examples of exactly the kind of problem you are trying to solve.
jquery requests are asynchonize by default , so your code does not wait for the response , so you have no guarantee that code after request will execute after the response , so you can set the request synchronize by set the async property false , now the request is synchronize and you can gurantee the rest of the code will execute after the response from the server ,
like this .
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,,
async:false,
success: handleResponse
});
I find myself having to get around waiting for AJAX in jQuery often these days. Problem is, I have to do loops and crap to wait for them. What are some ways that I can wait for the AJAX event to finish before executing code (preferably without making extra functions)?
Generally, if there is a chance that a repeating AJAX request may not be finished before it is called again, I use a flag to prevent overlapping requests.
First, define the flag and set it initially as false. Whenever you are sending your AJAX request, check to see if this flag is false. If it is, then proceed with the request - not before setting the flag to true mind. Once the AJAX request has completed, set the flag back to false.
Using the above method, only one instance of the AJAX query will run at once. I'm sure jQuery must have a way of seeing if there is an AJAX request being processed already or not, but I'm a MooTools man.
What method are you using to make AJAX calls? If you use the built in $.ajax(), you can set the success property to a callback function which will be called once the AJAX request returns successfully. There is also the complete callback which will always be called whether it succeeds or fails.
From the jQuery API:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
There is also a complete option that you can use.
http://api.jquery.com/jQuery.ajax/
Newbie here..
I just want to ask how can I accomplish my homework in school.
I basically have this need.
I want to send an ajax request every 10 seconds but I dont want to initiate another request if my previous request has not returned yet.
I am thinking that the connection to DB might be that bad sometimes so I would like to wait for my previous request to be finished (success/failed/error) before I fire up another.
I check on javascript and and found the setinterval method. But how can I line up my ajax request so that the server doesnt get fired up by many ajax request?
I am studying jquery right now and is using JSON.
One method would be to set a variable to false when you send out a request. When you get it back set it back to true. When you go to send out a new ajax request make sure the value is true. If not add it to a queue of some sort so that it will be called when the request is finished. However if every request takes longer then ten seconds your queue will get pretty backed up. So you may not want a queue. So instead when you go to send out the ajax request if the variable is false you just wait another ten seconds.
I'll even help more:
var isWatingForResponse = false;
$.ajax({
url: 'wherever'
,dataType: 'json'
,beforeSend: function() {
if(isWatingForResponse) {
return false;
}
isWatingForResponse = true;
}
,complete: function() {
isWatingForResponse = false;
}
,success: function (data) {
//process data
}
});
Or follow #qw3n answer. This should work with jQuery 1.4.2
As I see the OP question:
How to set up fault-tolerance on the client-side because of Db-server issues, using jQuery Ajax?
This IMHO, is a really good question.
If I may, I would like to map out the pipe:
web-client->network->web-server->network->Db-server
Db-server->network->web-server->network->web-client
Your solution to this problem of handling issues with the db-server in the client is workable, but really does not address the actual problem. It could really cripple you for future extension of your client.
You should really be handling this issue as close to the problem as possible. In the web-server.