How to kill or cancel an asynchronous call in javascript? - 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/

Related

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

How to get the data value during Jquery Ajax calling?

I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});

AJAX POST JSON value

I have AJAX POST, the result is JSON:
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var upload = JSON.stringify(result);
console.log(upload);
}
});
The upload result is:
{"Link":0,"Title":"d","Description":"dada","Keywords":"dad"}
How can I get the value of Title?
Do not stringify the result, just use result.Title.
As you already have JSON string, It's simple as a pie!
All you need to do is to call the property you want from the variable you assigned your result to.
for example:
var post_response;
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
post_response = JSON.stringify(result);
console.log("Title: "+post_response.Title);
}
});
hope this helps.

jQuery AJAX from different URLs

I am writing a Javascript program which can query data from more than one servlets each sec. If it queries from one servlet, I know how to do it in xxx.js file:
var TPS_URL = "http://localhost:8888/tps";
var jQueryFunction = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction,1000);
But now I have another servlet to query. How can I add another servlet into this js file? Just simply create another "TPS_URL_2" and "jQueryFunction_2", and do the same thing above?
var TPS_URL_2 = "http://localhost:9000/tps";
var jQueryFunction_2 = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL2,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction_2,1000);
??
Also, if I get a result from the first url and also another result from the other url, and I want to SUM them together, how can I do it?
set the URL as a parameter to the function and call this function as many times as you need
var jQueryFunction = function(xurl)
{
$.ajax
({
type: "GET",
async: false,
url: xurl,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
Call it like this
setInterval( function(){ jQueryFunction('some url') },1000);

Response/callback for JSONP using jQuery $.ajax not working

I am unable to catch response from C# to jQuery using $.ajax. I get an error "SCRIPT ERROR". How can I catch response using JSONP? This is what i am using:
$.ajax({
async: true,
context: mrq,
cache: false,
type: "GET",
url: MYURL,
crossDomain: true,
dataType: 'jsonp',
data: MYDATA,
processData: false,
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: function (jsonText, textStatus) {}
});
As far as I understand, dataType: 'jsonp' means that as soon as it's returned it's put into the callback function as an argument. So, I'd try this:
onJSONPsuccess = function(response) {
// do something with response, e.g.
results = response["results"]
}
$.ajax({
crossDomain: true,
dataType: 'jsonp',
data: { /*params you're sending in*/ },
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: onJSONPsuccess
});
You say the server side is C# - are you using WCF? There's a great article here about it:
http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
Basically you need to set up WCF (or whatever server-side code you're using) to return the json wrapped in a call to your callback function.
However, with jquery, you can simply add "?Callback=?" to your URL, change the dataType to 'jsonp', and forget about the rest of that stuff. You don't need the jsonp or jsonpCallback options set.
In contrast to a json request, the jsonp request will return your data not wrapped in a 'd' property, so your call back function is:
function(data) { var a = data.myProperty ... }
rather than
function(data) { var a = data.d.myProperty ... }
and the whole method is along the lines of:
var url = configuration.serviceUrl + "/" + method + "?callback=?";
var options = {
type: 'GET',
url: url,
data: args,
dataType: "jsonp",
contentType: "application/json",
success: function(data) {
if (callback != null) callback(data);
}
};
if (typeof errorCallback != 'undefined')
options.error = errorCallback;
$.ajax(options);

Categories