Javascript ajax request callback without waiting for response - javascript

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.

Related

How to send ajax request on one page and receive response on another page

I'm trying to send Ajax request using jquery and HTML5.
I have several pages in my application.
Is it possible to make Ajax request on a page(e.g sync.html) and receive response on a different page(e.g home.html).
I know there are other approaches to this like web-sockets and long pooling but if it's possible to achieve this using Ajax then that will make my work easier preventing me from changing any server configurations.
I'm using ASP.NET,C# on the server side.
The reason why I'm doing this is to prevent users from waiting for the response before they resume doing any other activity because this might take long depending on the size of data sent to server and the internet speed.
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: server_url,
data: {
number_chunksdone : num_chunksdone,
sync_data: round_1_sync_data,
organisation_id: organisation_id,
sync_id: sync_id,
instrument_id: instrument_id,
user_id: user_id,
sync_data_2: round_2_sync_data
},
success: function (j) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Any idea?
You can try writing Location.replace() or Location.assign() method inside success function. For e.g., document.location.replace('home.html');
The Location.replace() method replaces the current resource with the one at the given URL.

abort the right ajax

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.

How do I call a JS callback when a file upload completes?

I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.

Javascript Synchronization with JSON Requests

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
});

Preferred method for waiting for AJAX in JavaScript

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/

Categories