Start ajax request when other ajax request is running - javascript

In C# .NET it seems not to be possible to run 2 ajax request simultaneous. This is my Javascript code:
function startAjaxRequest1() {
setTimeout(startAjaxRequest2, 2000);
$.ajax({
type: "POST",
url: "/test.ashx/status",
contentType: "text/html; charset=utf-8",
dataType: "html",
async: true,
success: function (response) {},
failure: function (response) {}
});
}
function startAjaxRequest2() {
$.ajax({
type: "POST",
url: "/test2.ashx/statusupdate",
contentType: "text/html; charset=utf-8",
dataType: "html",
success: function (response) {},
failure: function (response) {}
});
}
When Ajax request 1 is executing, request 2 (started after 2 seconds), will never start. When I remove request 1, request 2 is executed is performing well.
Is it not possible to start a second ajax request when another is buzzy?
UPDATE:
In fact, this is my first ajax request (send files to server). Maybe it has something to do with this. The second ajax request keeps requesting each 4 seconds untill $.ajax(options) hass succeeded and the inner Ajax request is started. From that time, second request stops requesting. If I remove the inner Ajax request, there is no problem.
var options = {};
options.url = "/uploadGeoJsonFiles.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) {
$.ajax({
type: "POST",
url: "/dashboard.aspx/importGeoJsonData",
data: jsonString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
}
});
};
options.error = function (err) {
showError(err.statusText);
};
$.ajax(options);

Related

Ajax jquery to stop running when windows is closed

All,
I am new to MVC. I have built an application where a button click performs
get market data (lengthy operation).
data message and upload to database.
This is what the JavaScript function looks like:
function OnClick(s, e) {
if (true) {
$.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
What is happening right now is - When users close the browser in the middle of the run, controller action is still running. I can see that in my log.
How do I make browser close to stop running my controller action DataFileUpload ?
Thanks for helping out.
you can use the abort function from the XMLHttpRequest that $.ajax() returns.
abort(). If the request has been sent already, this method will abort the request.
Something like:
var xhr;
function OnClick(s, e) {
if (true) {
xhr = $.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
function closeBrowser() {
xhr.abort();
}
but this will only cancel the event on the client. You should also cancel the request on the serverside.

How to set the some specified time to ajax call ,So that if request is taking time retrieve the data ,It should come to the FAIL Block

var ajaxRequest = new enyo.Ajax({
cacheBust: false,
contentType: 'application/json;charset=utf-8',
method: 'POST',
timeout: 8000,
async: false,
handleAs: 'json',
data: JSON.stringify({
// Data to connect to the external service.
url: url
method: 'GET',
contenttype: 'application/json;charset=utf-8',
content: 'username=l&pwd=p' + searchParams
}),
success: function (inSender, inResponse) {
},
fail: function (inSender, inResponse) {
}
ajaxRequest.go(ajaxRequest.data).response('success').error('fail');
};
lets say ,call to the webservice taking 5 to 6 seconds time or if there is slow internet connection ,How to redirect to fail block
what about manually call to fail-callback-func, something like:
var getDataFail = true;
function getData() {
setTimeOut(fileCallbackFunc, 6000);
$.ajax({
url: yourURL,
success: doneCallbck,
error: doneCallbck,
//other ajax params
});
}
function fileCallbck() {
if (getDataFail) {
//your fail logic...
console.error('get data fail');
}
}
function doneCallbck() {
getDataFail = false;
console.error('get data done');
}

How to kill or cancel an asynchronous call in javascript?

I'm sending the following request to an MVC controller:
var datum = { param1: value, param2: value, param3: value };
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
dataType: "json",
data: JSON.stringify(datum),
success: function (response)
{
var result = response;
}
});
Sometimes response takes too much time. I'm looking for a way to kill or cancel this request. How can I achieve this?
jquery .ajax returns normalized XMLHttpRequest, just use its abort method:
var xhr = $.ajax(params);
xhr.abort();
My suggestion, use the timeout property:
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
timeout: 100000, //cancels automatically after 100 seconds
dataType: "json",
data: JSON.stringify(datum),
success: function (response)
{
var result = response;
}
});
You can use .abort() to cancel the request:
var xhr = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
dataType: "json",
data: JSON.stringify(datum),
success: function (response) {
var result = response;
}
});
xhr.abort();
https://api.jquery.com/jQuery.ajax/
you could use timeout property for ajax to cancel the request if it takes too much time
Refer http://api.jquery.com/jQuery.ajax/

Ajax Call waiting for the response of another Ajax Call?

I have two ajax call that cannot be done in one call. When the first ajax call starts the second ajax call can start immediately or whenever the user presses a send button. If the second ajax call starts he has to wait for the response of the first ajax call because he needs data from it.
How can I achieve that the second ajax call sends his request only after the first ajax call's response has been arrived?
Is there another way than setTimeout?
Can I register a listener for ajax call 2 on ajax call 1 somehow?
My code would be:
var xhrUploadComplete = false;
// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
xhrUploadComplete = true;
}
});
// ajax call 2
if (xhrUploadComplete) {
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
...
}
});
}
Edit: The second ajax call cannot be posted in done() or complete() of the first call, because it depends on the users choice to send the final form. The purpose of this two step process is to send an image to the server just after the user had inserted it to an input type=file.
Edit: In know that I cannot the the if(..) because this is an async call. I wrote it to make clear what I need to do. I think I need something like a future in Java.
xhrUploadComplete will be set to true asynchronously (in the future, when the request has finished) so your if-condition (that is evaluated right after the request is started) will never be fulfilled. You cannot simply return (or set) a value from an ajax call. Instead, move the code that waits for the results into the handler that would have set/returned the variable:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
…
}
});
}
});
With the Promise pattern you can compose those even more elegantly:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false
}).then(function(response) {
var returnedResponse = JSON.parse(response.responseText);
return $.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false
});
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
Maybe you need also need this:
var ajax1 = $.ajax({
url: url, …
}).then(function(response) {
return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
// as soon as ajax1 will be or has already finished
ajax1.then(function(response1) {
// schedule ajax2
return $.ajax({
url: url2, …
})
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
});

Jquery Ajax Call, doesn't call Success or Error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I return the response from an asynchronous call?
I am using Jquery Ajax to call a service to update a value.
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesn't go here
},
error: function (textStatus, errorThrown) {
Success = false;//doesn't go here
}
});
//done after here
return Success;
}
and Service:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.
I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;
Can't seem to find what's the problem with the code.
Update:
adding async: false fixed the problem
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous function. Otherwise you will have to make a callback.
So I just added async:false, to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object

Categories