Ajax jquery to stop running when windows is closed - javascript

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.

Related

Start ajax request when other ajax request is running

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

Calling web service from code behind instead of javascript

I have a javascript code that calls a web service from another server, it's working, but i need to call it from code behind due to an http call request issue, following my code :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://10.8.111.12:7181/CatchEventLink.asmx/CollectDataLink",
data: JSON.stringify({ "pDataDictionnary": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
//alert('success');
}
},
error: function (exception) {
//alert('Exeption : ' + exception);
}
});
Any suggestions please??

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

Ajax redirect on error

I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}

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