I am trying to make an ajax call and it returns something like, a JSON object;
{
id: 6,
success: "true"
}
My ajax call is :
window.foobar = function(foo){
$.ajax({
url: "http://foobar.com/sites/foo/",
dataType: "jsonp",
success: function (data) {
alert(data);
},
error: function () {
}
});
}
This ajax call is cross site call.
On chrome it gives: Uncaught SyntaxError: Unexpected token :
On firefox it gives:
invalid label
http://localhost:8080/sites/foo/?callback=jsonp1324336100888&_=1324336100894
Line 1
But when I calling from the same domain it works fine.
If you are claiming to support JSONP, you need to actually support it. Your code is valid JSON, but it is not valid Javascript: a response to a JSONP request must be valid Javascript. (To be precise, your code is invalid because the {} delimit a block, rather than an object literal.)
If you implement JSONP, you need to wrap the data in a call to a function whose name is given in the URL, in the callback parameter. So in this case, you need to post the following code:
jsonp1324336100888({
id: 6,
success: "true"
});
Obviously the precise name of the function you need to call depends on the callback URL parameter.
Related
I am trying to grab data from a wordpress blog using the WP-API plugin. My js file is using jQuery to make ajax calls to the api. I need to use JSONP as the response type since I am trying to access cross domain information.
When the page loads, I get an error "Uncaught TypeError: number is not a function" and my response begins like this: /**/1([{"ID":231,"title":blahblahblah... with the error pointing at the "1" in the console.
This is the code I am using to try and grab the data and parse it:
function get_posts(num_offset) {
offset = num_offset,
url = 'http://www.example.com/wp-json/posts?_jsonp=1&filter[posts_per_page]=5&filter[offset]=' + offset;
$.ajax({
type: 'GET',
dataType: "jsonp",
url: url,
success: function (data) {
consol.log(data);
console.log(url);
}
});
// second ajax call to get the total number of posts
$.ajax({
type: 'GET',
dataType: "jsonp",
url: 'http://www.example.com/wp-json/posts?_jsonp=1&filter[offset]=-1',
success: function (data) {
console.log(data);
}
});
}
I guess I need to know how I can remove the "Uncaught TypeError: number is not a function" error and then how I would be able to parse the JSONP data.
much thanks!
You're telling the other end that your callback's name is 1, in your URL:
http://www.example.com/wp-json/posts?_jsonp=1&filter[offset]=-1
Here --------------------------------^^^^^^
You want to use the name of the callback function you have on your page that you're expecting to receive the JSONP response, which needs to be a validate identifier literal (so not 1).
Because you're using jQuery, it's best by far if you let jQuery worry about what the callback name should be, by leaving off that query parameter entirely and letting jQuery add it. Since _jsonp is an unusual query string parameter name for this, you'll need to tell jQuery what the parameter name is.
$.ajax({
type: 'GET',
dataType: "jsonp",
url: 'http://www.example.com/wp-json/posts?&filter[offset]=-1',
// No _jsonp=1 here ------------------------^
jsonp: '_jsonp',
// ^^ new parameter here
success: function (data) {
console.log(data);
}
});
I am trying to get some data from a web service via ajax using the below function,
but I get this response message:
{"readyState":4, "status":200, "statusText":"load"}
The WS is supposed to return an array of json and, if I look in my chrome dev tool
in network tab -> Response, I actually get the proper array of json.
Question:
Why am I getting the result in my errorFunction callback?
function callWebService(wsUrl, params, successFunction, errorFunction) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Methods', ' GET');
xhr.setRequestHeader("Content-Type",
"application/json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: wsUrl,
data: params,
dataType: "json",
contentType: "application/json",
success: successFunction,
error: errorFunction
});
}
Here is my console.log when I use this error function function(jqXHR, status, error)
*Resource interpreted as Script but transferred with MIME type text/html: "http://www.myweb.it/services/service.php?callback=jQu…y21109160579217132181_1405523828314&codice_istituto=150201&_=1405523828315". jquery.js:8691send jquery.js:8691jQuery.extend.ajax jquery.js:8152callWebService global.js:5(anonymous function) index.js:49jQuery.event.dispatch jquery.js:4409elemData.handle jquery.js:4095
an error occurred: index.js:52
parsererror index.js:53
Error {stack: (...), message: "jQuery21109160579217132181_1405523828314 was not called"}message: "jQuery21109160579217132181_1405523828314 was not called"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: d index.js:54
readyState: 4 index.js:56
jqXHR.status: 200 index.js:57
jqXHR.statusText:load index.js:58
jqXHR.responseText: undefined*
You're seeing the error callback fired because there's something wrong with your AJAX request, and it's not returning successfully. Identifying why this happens is another matter.
The first argument jQuery passes to your error callback is the jqXHR object:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
This is different from the success callback, which begins with the data returned:
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
jqXHR is a superset of the xmlHttpRequest object JavaScript returns. Inside it, you're seeing readyState of 4, which simply means "done", and status of 200 means a successful request. So, at least you know you're probably pointing your request at the right URL.
You should be able to get other information from your jqXHR object which might help you identify the cause of the error. From the docs:
For backward compatibility with XMLHttpRequest, a jqXHR object will
expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()
That object you're seeing is an XMLHTTPResponse; a representation of the actual AJAX request. You're getting it passed into your error handler because that's the first argument of jQuery's ajax error callback.
Figuring out why it's calling the error callback and not the success callback is harder. That statusText suggests that your server returned the string 'load' - is that a possibility? Another common problem is if your data isn't actually valid JSON. JSON's quite a picky format; if you're producing it yourself, you might have invalid whitespace or the wrong kind of quotes (or completely missing quotes). Check your data with a tool like JSONLint and make sure it's valid, and make sure that your server is only returning JSON - nothing else in the response body.
Just a work around
1. remove dataType:'json'
2. parse json in success function call
data = $.parseJSON(data);
OK I'm using PHP and the Facebook JS API to post stories on users' pages with jQuery's $.ajax() function and it's working fine everywhere except in Chrome.
Chrome is returning the error "SyntaxError: Unexpected Token : ".
I have it alerting the XHR response on error and it is as follows:
{
"id" : "30800681_37922830145443"
}
which is valid JSON. It can't be anything I'm doing wrong with the JSON result because it throws the error before any parsing can be done (i.e., it's not making it into the 'success' function).
The code that's behind this is as follows:
if ($('#post-facebook').is(":checked")) {
// Do the FB post
$.ajax({
type: "POST",
url: "https://graph.facebook.com/<?= $this->session->userdata('fb_id') ?>/feed",
data: "message=" + $("#upload-caption").val() + "&access_token=<?= $this->session->userdata('fbtoken'); ?>&app_id=<?= $this->config->item('appId') ?>&link=" + post_url,
success: function(msg) {
// Save the FB post ID to the DB
var result = $.parseJSON(msg);
var result_array = result.id.split("_");
// Do more stuff here, but it's not even getting into this success function
},
error: function(xhr,ajaxOptions,thrownError) {
// This is what's executing because the thrown error is getting alerted
alert(thrownError);
}
});
}
When I add dataType: "json" in the Ajax parameters, it still goes through the Error function but the thrownError parameter is empty.
I am pulling my hair out...any suggestions? Thanks in advance,
Using jQuery with post is not possible as POST require CORS support, and that is not readily available.
Use FB.api instead, which handles all of this for you, in a much better way.
I can't figure out what is wrong here.
$(function() {
$('#cars').change(function() {
var cars = $('#cars').val();
$.getJSON('http://fooobar.com/data.php?id='+cars, function(data) {
alert('test');
});
});
});
Request to http://fooobar.com/data.php?id=3 returns json string like this
[{1: "sdadd"}]
The problems is that code
alert('test');
is not executed when request to data.php returns correct json string but is executed when no data is returned.
What I miss ?
[{1: "sdadd"}]
is not a correct JSON string. You can't have numbers as keys in objects and these keys can't start with a number.
That's why jQuery doesn't execute your success callback:
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
According to the documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently
You can try this to check if I'm right:
jQuery.getJSON(...).error(function() { alert("error"); })
I'd guess it's the Same Origin Policy, which stops a webpage calling AJAX on another domain.
You are using incorrect format to do a cross domain data request.
You need to do return JSONP data, not JSON .
For JSONP to work, your URL :
http://fooobar.com/data.php?id=3
which normally returns { "result" : "some data" }
when called with any callback function name ,eg :
http://fooobar.com/data.php?id=3&callback=myJavascriptFunction
should return : myJavascriptFunction( { "result" : "some data" } )
only then it can call your callback javascript function with JSON data.
example:
see the out of these two api calls to facebook api which supports JSONP format :
i) JSON :
https://graph.facebook.com/19292868552
ii) JSONP :
https://graph.facebook.com/19292868552?callback=myFunctionName
Read more here : http://api.jquery.com/jQuery.getJSON/
Same origin policy is the problem here, as others have said.
But here's what they didn't say - how to fix it:
$.ajax({
url: "someurl.com",
dataType: "jsonp",
data: {'some key':'somevalue', 'someotherkey':'val'},
success: function(response) { alert(response); },
error: function(jqXHR, textStatus, errorThrown) {
//do some error handling
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
});
Here I'm using the $.ajax method - basically $.getJSON is a wrapper for this with dataType:'json'.
Note: this will change your request so that it passes in a param called "callback" which will be completely random. This needs to be processed by the server and passed back as a function name: i.e
Your request:
someurl.com/?something=something&callback=123456
Should return:
123456({ "key":"value"});
And that should allow you to get the returned data as normal.
Reference:
The bit on JSONP and the various options that can be used in $.ajax is quite good here:
http://api.jquery.com/jQuery.ajax/
Wikipedia has an alright article on it here: http://en.wikipedia.org/wiki/JSONP#Padding
Edit: also doing the request like this and using an error function will allow you to throw any errors to the console or alert boxes, so you can check if your returned JSON is valid or not too. Markup edited to throw an alert box on failure.
So I'm trying to make a request to the Stack Exchange API with the following jQuery code:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.
Furthermore, you can't do POST with JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).
There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.
The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.
Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme
"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).
By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.
Result from calling the URL:
callme({
"statistics": [
...
]
})