Jquery Send Ajax and no wait response for sending other ajax - javascript

I have an ajax that call to a server and run a long process (this process is writing the status on a database).
I have other ajax (recursively) to get the status of the long process and set the params on a Progress Bar.
My problem is that the second ajax not start until the first one finishes. Is there a way to send the first ajax and no wait for a response?
Any ideas?
I appreciate any suggestion, I am a little bit tired about this issue.
If there is another method to send a long process and get the status of the long process, tell me, please.
Thank you!
This is my code, in case it's helps
executeProgressBar(1, token);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: "/long_process",
data: form_data,
success: function (response) {
//NOTHING
}
});
function executeProgressBar(start, token) {
if (start == 1) {
//reset progress bar
$('.progress-bar').css('width', '0%');
$('.progress-bar').text('0%');
$('.progress-bar').attr('data-progress', '0');
}
$.ajax({
type: "POST",
url: "/progress_bar_status",
data: { token: token, sleep: 0 },
success: function (response) {
$('.progress-bar').css('width', response['percentage'] + '%');
$('.progress-bar').text(response['percentage'] + '%');
$('.progress-bar').attr('data-progress', response['percentage']);
$('#done').text(response['executed']);
$('.execute-time').text('tiempo');
if (response.percentage == 100) {
$('.end-process').show();
} else {
executeProgressBar(0, token);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'parsererror') {
textStatus = 'Technical error: Unexpected response returned by server. Sending stopped.';
}
alert(textStatus);
}
});
}
EDIT
I solved whit this code on the server side - php
/************** Close connection and return echo message **************/
ob_end_clean();
header("Connection: close");
ignore_user_abort(true);
ob_start();
echo('text response to ajax');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
// if you're using sessions, this prevents subsequent requests
// from hanging while the background process executes
if (session_id()) {
session_write_close();
}
/************** background process starts here **************/
View in this post: How do I close a connection early?

You are calling the executeProgressBar instantly instead of waiting for the first AJAX call to complete. Call the executeProgressBar function in the success method callback and pass it to the executeProgressBar function and modify the parameters like the example below.
Be sure to build a check in that lets the recursive function know when to stop.
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: "/long_process",
data: form_data,
success: function (response) {
executeProgressBar(1, token, response);
}
});
function executeProgressBar(start, token, response) {
if (start == 1) {
//reset progress bar
$('.progress-bar').css('width', '0%');
$('.progress-bar').text('0%');
$('.progress-bar').attr('data-progress', '0');
}
$.ajax({
type: "POST",
url: "/progress_bar_status",
data: {token: token, sleep: 0},
success: function (response) {
$('.progress-bar').css('width', response['percentage'] + '%');
$('.progress-bar').text(response['percentage'] + '%');
$('.progress-bar').attr('data-progress', response['percentage']);
$('#done').text(response['executed']);
$('.execute-time').text('tiempo');
if (response.percentage == 100) {
$('.end-process').show();
} else {
executeProgressBar(0, token, response);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'parsererror') {
textStatus = 'Technical error: Unexpected response returned by server. Sending stopped.';
}
alert(textStatus);
}
});
}

Related

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Post request is succeeding according to database but failing according to Ajax block

I am posting to my database (for context using GAE, and Objectify as a DAO) and it posts correctly (and the backend returns a response of 202), however, under the Ajax it is not calling the "success" block (i.e. in the method below even when it post's correctly, it calls alert("error1")). The source code for Ajax says a Post is supposed to call the success block when the status is between 200 and 300. Any ideas why it isn't working? Any help would be great!
function userExist() {
var rootUrl = "http://localhost:8888/api/";
function loginToJSON() {
return JSON.stringify({
"username": $('#username').val(),
"password": $('#password').val()
});
}
//System.out.println(loginToJSON());
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootUrl + 'userLogin',
dataType: "json",
data: loginToJSON(),
success: function(data, status, jqXHR) {
alert("success");
},
error: function(jqXHR, status, errorThrown){
alert("error1");
}
});
}
The relevant java backend is
#POST
public Response login(Login l) {
if (loginService.checkCred(l)) {
return Response.status(202).build();
} else {
return Response.status(403).build();
}
}

Jquery Ajax callback not working calling success and failed

I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks
You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);

How to show progress bar when calling AJAX?

I am developing a mobile app using phonegap (JQ + Html ). In my app, consuming REST webservice using AJAX calls.When service invoke, I am showing a progress bar animated GIF image . The problem is, browser freezes when calling AJAX. So the progress bar is not showing.
In ‘beforeSend’ i am showing the progress bar image and after ‘complete’ i am hiding the progress bar image.
I am also trying async: true . But it execute service as asynchronously. In my app, asynchronous execution is not suit. Because asynchronous execution will not wait for ajax executing. My app should wait until the ajax execution complete. In that process time I want show progress bar.
Here is my code.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
beforeSend: function() {
StartPBar():
},
data: JSON.stringify(RQ),
async: false,
url: URL,
complete: function() {
stopPBar();
},
success: function(res, status, xhr) {
try {
RS = res;
} catch (e) {
alert(e);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
Any suggestion to show the progress bar stay on screen until the process is fully complete? Any help would be appreciated. Thanks
Make sure you verify your javascript code.
Remove this code.
beforeSend: function() {
StartPBar():
},
Replace your jquery mobile with this one jQuery Mobile 1.4.0-rc.1
http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.js
Replace your code with this one.
$.mobile.loading('show');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
data: JSON.stringify(RQ),
async: false,
url: URL,
complete: function() {
$.mobile.loading('hide');
},
success: function(res, status, xhr) {
try {
$.mobile.loading('hide');
RS = res;
} catch (e) {
alert(e);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.mobile.loading('hide');
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
Try to set async: true, the async: false will freeze the browser until the request is completed. Also move the async: true before beforeSend method.
The async: true, when supported by browser, basically means: browser will send data asynchronous and will not block or wait other actions from executing. This is the only in my opinion way to show the progress bar indicator. Because (from the documentation):
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active.
If you want to wait until ajax requests done, you can do it also with async:true like;
StartPBar():
$.when(runAjax()).done(function(result) {
// result conatins responseText, status, and jqXHR
stopPBar();
});
function runAjax() {
return $.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
accepts: "application/json",
data: JSON.stringify(RQ),
async: true,
url: URL,
success: function (res, status, xhr) {
try {
RS = res;
}
catch (e) {
alert(e);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Excpetion " + errorThrown + XMLHttpRequest);
}
});
}
In this example, when ajax request completed, progressbar stop function will be called.

function calling ajax returns false

I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}

Categories

Resources