I'm running a long polling ajax that returns status of request. If failed, I need the ajax to stop. The ajax is written like this:
function someFunction(url){
$.ajax({
url: url,
success: function(data){
if(data.status == 'FAILED'){
//Need this ajax to stop
}
}
});
}
$('some-button').on('click',function(
var url = 'server-url';
someFunction(url);
));
I have to use the someFunction() function as this long polling method is being used by multiple other parts of the code. What should I be doing to stop this function?
try something like this
function someFunction(url){
$.ajax({
url: url,
success: function(data){
if(data.status != 'FAILED'){
//Need this ajax to stop
}
}
});
}
your ajax request is already completed in success. but if status is failed and you want to stop further execution of code than you can use not !
$.ajax returns a wrapped xhr object. Simply use:
var req = $.ajax...
..
req.abort()
var ajaxReq = null;
ajaxReq = $.ajax({
url: url,
success: function(data){
if(data.status == 'FAILED'){
//Need this ajax to stop
}
}
error: function (x, y, z) {
ajaxReq.abort();
}
});
And you can use ajaxReq.abort() to stop ajax call.
Related
I have a http long polling polling done like this:
xhr = $.ajax({
type: "GET",
url: "http://localhost/pubsub.php",
...
Ajax returns a xhr object. And I use it in another function to abort the long polling request by doing xhr.abort();
After I do this, how can I restart the long polling request? Is there a method to restart?
Thanks
Here is what I am doing in my projects,
If I see a long delay in the ajax response, I simply abort the previous ajax request and make a new request in the same method as shown below,
Note: I don't call the GetData() mmethod in any loop, rather it is a button click action (say refresh) from application user.
function GetData()
{
if (getDataAjaxCall && getDataAjaxCall.readyState != 4)
getDataAjaxCall.abort();
var searchRequest = {};
searchRequest.Criteria = []; //set some criteria
getDataAjaxCall = $.ajax({
url: 'api/DataController/GetData',
type: 'POST',
dataType: 'json',
data: searchRequest,
success: function (data, textStatus, xhr) {
//do tasks you want on success
},
error: function (xhr, textStatus, errorThrown) {
$.unblockUI();
if (textStatus != 'abort') {
//display error message on actual error
}
}
});
}
I hope the above lines of code might give you some idea.
Also, in the error callback, place a check to catch the abort and handle it separately.
There is no API present to restart the AJAX, But you can simulate the restart of AJAX by calling the AJAX again in error callback function.
var xhr;
function callAJAX() {
xhr = $.ajax({
url: "http://stackoverflow.com/dummyURL",
error: function (xhr, e) {
console.log("Error Occured " + e);
callAJAX(); // Restart the AJAX call
}
})
}
callAJAX();
xhr.abort()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I've been trying to figure this one out since my earlier question.
I can receive the data, as I see it under resources using Develop > Show Web Inspector on safari. But I can't seem to assign it successfully to a variable to use later on.
<script>
function getData () {
$.ajax
({
type: "GET",
url: "https://myjirasite.com/jira/rest/api/2/project/ON/versions?",
dataType: 'jsonp',
//async: true,
beforeSend: function (xhr) {xhr.setRequestHeader('Authorization', make_base_auth("myusername", "mypassword"));},
success: function (){
//Attempt 1 at outputting the result to an alert.
alert(JSON.parse(data));
}
});
}
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
</script>
In a second attempt I assign the ajax call to a variable and attempt to print that out to an alert. No success. the alert is empty
var jqXHR = $.ajax
({
type: "GET",
url: "https://myjirasite/jira/rest/api/2/project/ON/versions?",
dataType: 'jsonp',
async: false,
beforeSend: function (xhr) {xhr.setRequestHeader('Authorization', make_base_auth("myusername", "mypassword"));},
success: function (data){
alert(JSON.parse(data));
}
});
alert(JSON.parse(jqXHR.responseText));
I know that the issue lies with ajax calls being asynchronous, but I can't figure out how to write the callback such that I can get the json data into a variable to use later in via a different function.
Don't set async: false, as this will block the browser whilst your Ajax request is processed.
Instead, you can use promises, or call a further function from within your success callback.
Something like:
function getData(){
return $.ajax({
type: "GET",
url: "https://myjirasite/jira/rest/api/2/project/ON/versions?",
dataType: 'jsonp',
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', make_base_auth("myusername", "mypassword"));
}
});
}
getData()
.done(function (data){
console.log(JSON.parse(data));
})
.fail(function(){
console.log("Error!");
});
<script>
var getData = function() {
$.ajax
({
type: "GET",
url: "https://myjirasite.com/jira/rest/api/2/project/ON/versions?",
dataType: 'jsonp',
//async: true,
beforeSend: function (xhr) {xhr.setRequestHeader('Authorization', make_base_auth("myusername", "mypassword"));},
success: function (){
//Attempt 1 at outputting the result to an alert.
alert(JSON.parse(data));
getData.data= JSON.parse(data);
}
});
}
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
setTimeout(function(){console.log(getData.data);}, 3000); // Fire after 3 seconds to get data.
</script>
I don't think $.ajax actually returns anything - but I could be wrong. Either way, that's not too important, because you shouldn't rely on the results of an ajax call being available immediately. Your alert statement is firing before the Ajax request is finished - it sounds like you know that already.
When leveraging asynchronous calls (ajax), its a best practice to have any logic that relies on the data returned from the call to be done in (or triggered by) a callback (or as #Jack Zelig mentions, promises). This is what success parameter of $.ajax is all about. It will get called once the request completes successfully. You can also define complete and error callbacks - which fire once the request is complete (regardless of status) and once the request fails respectively.
So to summarize, your best option is probably this:
var jqXHR = $.ajax
({
type: "GET",
url: "https://myjirasite/jira/rest/api/2/project/ON/versions?",
dataType: 'jsonp',
success: successHandler
});
function successHandler(data) {
alert(JSON.parse(data));
}
In this way, only once data is received will an alert be shown that will contain the data.
I have a for loop in java script :
for(i=1;i<=10;i++){
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
}
});
}
this script send all of ajax request Simultaneously !
But It makes problem for me ...
how can i can prevent continue for loop when ajax is working ?
If you need the requests to be executed in serial instead of parallel, you can do that with a little re-structuring. Don't make the AJAX requests synchronous, just use the response of each request to invoke the next one.
Consider a structure like this:
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
}
});
}
Now the request is wrapped in a function that you can invoke. So invoke it in response to the previous request:
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
sendRequest();
}
});
}
It's starting to look like a standard recursive pattern, so all you need now is a terminating condition. Similar to the original loop, just use an incrementing value:
var i = 1;
function sendRequest() {
$.ajax({
type: "GET",
url: "insert_names.php",
success: function (data) {
// some codes
i++;
if (i <= 10) {
sendRequest();
}
}
});
}
Then just invoke it once to start it:
sendRequest();
Now the request should be invoked 10 times as expected (unless my math is off by one, but that should be easy to correct), each request happening in response to the previous request.
With asynchronous programming, don't try to make it synchronous. Instead, perform actions in response to the callbacks.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an AJAX function that is called from a javascript function.
Something like this:
(CODE1)
//javascript function calling AJAX.
var function check(){
var status = chkHoliday(date,'Date Chosen');
alert('called');
return status;
}
//AJAX function
function chkHoliday(date,str){
var flag = true;
$.ajax({
type: "GET",
url: someurl,
async: false, //if commented, the alert() from the caller function is called before completion of this function.
dataType: "json",
success: {
flag = false;
}
});
return flag;
}
It works well. The only problem is that since async it is set to false, the web page sort of hangs for a while but then continues to proceed further.
To avoid this I read something about callback functions so i tried this out:
(CODE 2)
//javascript function calling AJAX.
var function check(){
var status;
chkHoliday(date,'Date Chosen',function(retVal){
status = retVal;
});
if(status != null){
alert(status);
return status;
}
else{
alert(true);
return true;
}
}
//AJAX function
function chkHoliday(date,str,callback){
var flag = true;
$.ajax({
type: "GET",
url: someurl,
//async: false, //if commented, the alert() from the caller function is called before completion of this function.
dataType: "json",
success: {
flag = false;
callback(flag);
}
});
//return flag;
}
this worked but the alert was called again before the AJAX function could complete stating "undefined". I don't know what I'm doing wrong.
I want, that the AJAX function should wait till it executes completely and then return to the calling function and run the next statements in the caller function with halting the process (i.e with the use of async). Also i want that the value returned by AJAX should be easily accessible to my caller function.
Put the alert inside the callback function:
chkHoliday(date,'Date Chosen',function(retVal){
status = retVal;
if(status != null){
alert(status);
}
else{
alert(true);
}
});
But note you cannot use the return statement anymore as what you have expected because it is asynchronous.
Since AJAX works asynchronous, it is a problem to place it in a function and return a value. To solve this use deferred with a promise. This will promise the ajax result to the caller. It is slightly different. Here is an example. Works like a charm for me.
Of course you will need to adapt it to your needs, but all you really have to do is create your data object.
var data = {}
function chkHoliday(data) {
var deferred = $.ajax({
method: "post",
url: ajaxURL,
dataType: "json",
data: data
});
return deferred.promise();
}
chkHoliday(data).done(function (response) {
console.log(response);
}
return from your php file with a
echo json_encode(array("success"=>"hello"));
Put the alert inside the callback
functions. or else alerts will work simultaneously inspite of success or error.
I have a strange issue in JQuery AJAX..
My Steps sequence are as follows:
1) I have a JS Function which I am calling on Button Click Event:
function Click()
{
//I am performing some Validations then making an AJAX Request:
$.ajax({
type: "POST",
url: url,
context: window,
data: datatoPost,
contentLength: contentLength,
async: true,
success: function (response) {
callbackFn(response);
},
error: function (msg) {
this.error = msg;
}
});
// The callback function is called on Successfull AJAX Request
// i.e. callbackFn (See below)
// I am then checking the window.IsValid which I have set in below function;
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
function callbackFn(response)
{
if(response == 'Valid')
{
window.IsValid = true;
}
else
{
window.IsValid = false;
}
}
2) Now, The Problem is while server is processing the First AJAX Request then the code written after that i.e.
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
is executed
3) I get window.IsValid = false as first AJAX Request's callback function i.e. callbackFn(response) is not called yet and Even after a Valid response of first AJAX request my second ajax request is not getting executed as window.IsValid variable is not still got set in callback function as callback is not called yet due to server is processing the request.
Please help me I am stuck..
you should then use
async: false,
in you ajax function call. Which is not recomended. The better thing will be to use
if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}
within your callback function.
Because your post is asynchronous, the script continues to execute whilst the ajax request is being processed.
Instead, you need to move your tests for window.IsValid into the success function:
function Click()
{
//I am performing some Validations then making an AJAX Request:
$.ajax({
type: "POST",
url: url,
context: window,
data: datatoPost,
contentLength: contentLength,
async: true,
success: function (response) {
callbackFn(response);
if (window.IsValid == true) {
// Then Perform another AJAX Request
// best done as another function.
}
else {
// do nothing
}
},
error: function (msg) {
this.error = msg;
}
});
}