jQuery ajax abort after request sent - javascript

Probably best to revise the question:
I have an ajax call in my code and I want to cancel the call immediately after it is sent. Basically, I don't want to wait for a response, I just want the entire request to be sent from the client. Could anyone provide some ideas on how to accomplish this?
I have tried the following in Chrome, however it seems that the request is never actually sent (I am logging received requests on the server side).
Basically:
var sendRequest = jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
success: function(result) {}
});
sendRequest.abort();
I have also tried setting a timeout of 1, but bizarrely if I load the page from a new browser the request is not sent (if I refresh the page it is sent).

As easy as just:
jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {/*run awesome code*/}
success: function(result) {}
});
// call whatever you want after send
afterSend();
So there is no built in jquery.ajax event for that but you may just call the function right after $.ajax();

Just call YOUR_COOL_FUNCTION after your code block.
This will work because ajax requests use callbacks, so it will not block the current execution for the sake of the performed request, but it will make the request, then move on to your code, so it's as simple as putting any desired block of code after this AJAX call.

Related

How to run getJSON synchronously? [duplicate]

GOAL: What I'm after is to get data from database and refresh main.php (more evident through draw_polygon) every time something is added in database (after $.ajax to submit_to_db.php).
So basically I have a main.php that will ajax call another php to receive an array that will be saved to database, and a json call another php to return an array will be used by main.php.
$(document).ready(function() {
get_from_db();
$('#button_cancel').click(function(){
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: {list_item: selected_from_list},
success: function(result){
...
get_from_db();
}
});
});
function get_from_db(){
$.getJSON('get_from_db.php', function(data) {
...
draw_polygon(data);
});
}
});
In my case, what I did was a get_from_db function call for getJSON to actually get data from database, with the data to be used to draw_polygon. But is that how it should be done? I'm a complete newbie and this is my first time to try getJSON and ajax too to be honest. So my question: How does asynchronous work actually? Is there another workaround for this instead of having to call function get_from_db with getJSON (it isn't synchronous, is it? is that why it doesn't update the page when it isn't within a function?) All the time - like $.ajax with async: false (I couldn't get it to work by the way). My approach is working, but I thought maybe there are other better ways to do it. I'd love to learn how.
To make it more clearer, here's what I want to achieve:
#start of page, get data from database (currently through getJSON)
Paint or draw in canvas using the data
When I click the done button it will update the database
I want to AUTOMATICALLY get the data again to repaint the changes in canvas.
Since $.getJSON() uses ajax configurations, just set the global ajax configs:
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
// Your $.getJSON() request is now synchronous...
// Set the global configs back to asynchronous
$.ajaxSetup({
async: true
});
Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:
async: false,
So for example:
$.ajax({
url: "myurl",
async: false,
...
})
$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So just rewrite your request in terms of that and async:false will work just as you expect.
$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):
$.ajax({
dataType: "json",
url: url,
data: data,
async: false,
success: function(data) {
...
draw_polygon(data);
}
});
Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation. Note that synchronous requests may temporarily
lock the browser, disabling any actions while the request is active.
You might want to try jQuery Deferreds like this:
var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
...
draw_polygon(data);
});

How can i stop hanging page when a request is send via Ajax

I am facing a serious issue... Whenever i use Ajax to send a request and get an response my browser got hanged.. and show no loading etc...
But when i response is retrieved from the Ajax then browser and page again start working...
Below is the code that i used.....
function ShowContestStatus(contestID)
{
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url:"process/processMyContest.php",
type:'POST',
cache:false,
async:false,
data : {act : 'showcontest', cid : contestID },
success:function(result)
{
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Please help me on this... i want to get the same response as on other websites when you send a request and they are using ajax the page neither hanged and also each processing like scrolling etc is visible ......
So please suggest me good ideas.... so i can get rid of it and make my ajax smooth for page without effecting and irritate the other person by hanged...
Thanks in advance...:)
The problem is async:false... Since your ajax request is synchronous the script execution will wait for the request to complete to continue..
Since browser uses a single threaded execution pattern(either it will execute script or repaint or wait for user events at a time- not all at the same time), your browser tab will stop listening to user(so it will look like it is hanged)
function ShowContestStatus(contestID) {
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url: "process/processMyContest.php",
type: 'POST',
cache: false,
//remove async: false,
data: {
act: 'showcontest',
cid: contestID
},
success: function (result) {
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Ajax.async
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation. Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active. As of jQuery 1.8, the use of async: false with jqXHR
($.Deferred) is deprecated; you must use the success/error/complete
callback options instead of the corresponding methods of the jqXHR
object such as jqXHR.done() or the deprecated jqXHR.success().
Make async:true for making the browser listen other events while running the ajax code.

execute a PHP script from Ajax without expecting an answer (and no daemons)

I hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.

Efficient way of passing data and calling background script in PHP

I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories