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

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

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

Cross domain Ajax Call

While calling MVC webservice from my html page it was always going to error; please help me
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (msg) {
alert(Response.ErrorMessage )
},
error: function (e, status) {
alert(e + " Fail " + status)
}
});
You have to setup CORS (http://www.html5rocks.com/en/tutorials/cors/) or use JSONP. If you decide to use JSONP then you have to send proper callback function name with JSON data.

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/

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

javascript jquery and using eval

i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...

Categories