How to get the response text from an AJAX request using jQuery - javascript

I am trying to make a JSONP request to a server. This is my code:
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function() {
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});//code indentation
When I run the code it errors. But if I open the developers tools in Chrome (ctrl+shift+I) I can see the request under "network". Clicking on it shows the correct response (and shows the request was accepted).
Apologies is there is a really obvious solution (I have tried searching, but with no luck), but at this point I am well and truly baffled. Any help would be really appreciated.
::EDIT::
changing the error function to:
error: function() {
console.log('error', arguments);
},
returned the message "jsonCallback was not called" Thanks to Aaron Digulla below.
The response from the server is JSON, not JSONP (checked with JSONlint)

When you say "it errors", my guess is that you get alert(2). To find out why, log the function arguments to the console:
...
error: function() {
console.log('error', arguments);
},
...
jQuery will pass additional information (like the error message) to the function. That should help you understand why it fails.
The same is true for the success function which gets the server response, for example.
[EDIT]
I get the error jsonCallback was not called
That means your server isn't returning JSONP. JSONP looks like name({...}) while normal JSON looks like {...}. Please check your server's configuration and make sure it actually supports JSONP and that the response looks correct.
I should have seen this from your code:
dataType: 'jsonp'
headers: {
'Accept': 'application/json', //this is required by the server
}
That means you're sending a JSONP/JSON mix which can't work. If you use a certain dataType, then let jQuery build the correct headers.

The success function has argument and from that argument you can get the response text.
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function(response) {
alert(response);
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});

You cannot set async: false for a jsonp request due to nature of it, adding script tag to handle response method.

dataType: 'jsonp
as you mentioned,the type of data that you're expecting back from the server is jsonp but may be your server will return any other format rather than jsonp.. so check it which type of response your server is returning in under Network in browser console... then if it is not jsonp format, change your respons return type....

Related

Cross domain issue when making ajax call from one site to another to get data from database

I am creating a site in which user can create popup on one site and then take small code to used on other site . Problem is when i am made ajax call from other site to fetch data in others site database i am getting error "No cross origin access allowed".When i am using jsonp it is giving me correct response but i am not able to collect it. It is giving me error"Unexpected token". I am using jquery ajax if you have any other idea then let me know i will implement it also. Here is my code :
$.ajax({
url: "url",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
jsonpCallback: 'callback',
type: 'GET',
data: {
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
If Your response has error server side Cross domain issue then your server side response should exist Access-Controll-Allow-Origin with * value will solve your problem.
You can try that:
crossDomain : true,
$.ajax({
url: "url",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
jsonpCallback: 'callback',
crossDomain : true,
type: 'GET',
data: {
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
It solved my problem here.

Correct use of JSONP

To successfully use JSONP (e.g. via jquery - $.ajax ... etc.) must always be that the requested page is designed to provide data corresponding to this format?
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also will I get an error?
This question might seem trivial to some users, but I'm starting right now to learn these technologies, and the matter is a bit complicated.
Based on these (ref1 ref2) references it would seem that there must be consistency between the request with JSONP and implementation of the server response.
Edit
I have this jQuery request
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
And I have loaded in https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1 this test.js file:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
When I am connected I hope to obtain as console's output: succeed succeed.
Instead this is what I get:
succeed
failed
Edit2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
The .js file:
myCall({ some : "data" });
The output:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1
To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?
Yes. A request for JSONP will only work if the response is expressed as JSONP.
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?
You can have a static JavaScript program that conforms to the JSONP format (it requires hardcoding the callback function name), so not necessarily.

JSONP via getJson not working?

I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

jQuery ajax jsonp call always get unexpected token error

I've been wasting a great deal of time for something I think is so simple, yet there are no good examples that illustrate how and what the ajax call is doing.
This is my javascript code:
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/timezone/json',
dataType: 'jsonp',
data: {
location: myLoc,
timestamp: myTime,
sensor: true
},
success: function(){alert('OK');},
error: function(){alert('FAIL');}
})
}
The variables "myLoc" and "myTime" are not the problem. In fact if I cut and paste the URI into my browser it works just fine and shows the data: https://maps.googleapis.com/maps/api/timezone/json?callback=jQuery18307430207263678312_1354817349576&location=36.7468422%2C-119.7725868&timestamp=1354817353&sensor=true&_=1354817353398
From what i've been reading, the "callback" parameter is automagically generated and somehow the code should be smart enough to call the success function or error function.
The error that chrome returns is "Uncaught syntax error unexpected token ':'"
The javascript code always calls the error function no matter what I try. I added a jsonpCallback parameter (didn't work), json parameter (didn't work), changed dataType to "json" (didn't work due to cross domain error).
Please help.
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/timezone/json',
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
data: JSON.Stringify({
location: myLoc,
timestamp: myTime,
sensor: true
}),
success: function(){alert('OK');},
error: function(){alert('FAIL');}
});

Categories