I'm very new to JSON and JSONP.
I've read through each of the posts that are recommend by the SO search for this error, but I can't seem to get a handle on it.
I have the following code to grab data from an EXTERNAL website:
$.ajax({
url: "https://url.com/authenticate?login=test&apiKey=test",
dataType: 'jsonp',
success:function(json){
console.log("login successful");
}
});
When I load the page, I get:
Uncaught SyntaxError: Unexpected token :
and when I click on the error in Chrome, I see
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
with a little red x after "true"})
From this, it seems as though I have succeeded in logging in, but I'm doing something else wrong because my console.log("login successful"); never fires. What am I doing wrong?
P.S.
I've tried dataType: 'json' but I get the No 'Access-Control-Allow-Origin' header is present as I'm on a different server, so I went back to jsonP as this is cross-domain.
I've also tried the above url as url: "https://url.com/authenticate?login=test&apiKey=test&callback=?", as I've read I need a callback, but I don't really understand what the functionality of callback is and either way, the error that gets returned (whether &callback=? is in there or not) is:
authenticateUser?login=test&apiKey=test&callback=jQuery111107732549801003188_1423867185396…:1 Uncaught SyntaxError: Unexpected token :
so it's adding the callback in either way....
Also, from the API I'm trying to access:
"this uses the REST protocol, and provides data structured as XML or JSON"
This is not a duplicate of the linked post as the information in the linked post does a great job of explaining what JSONP is, but doesn't answer my specific question regarding why I get data back (so my call is successful,) but why I still get an error and cause my script to stop.
The API you're sending the AJAX request doesn't implement JSONP. It ignores the callback= parameter, and just returns ordinary JSON. But when the browser tries to process this as JSONP, it gets a syntax error because it's not properly formatted. JSONP is a JSON object wrapped in a call to the specified callback function, e.g. it should be sending back:
jQuery111107732549801003188_1423867185396({...});
where {...} is the JSON object you're trying to retrieve. But it's just returning {...}.
You should implement this using a PHP script on your own server. It can be as simple as this:
<?php
$username = urlencode($_POST['user']);
readfile("https://url.com/authenticate?login=$username&apiKey=test");
Then your AJAX call would be:
$.ajax({
url: "yourscript.php",
type: "post",
dataType: "json",
data: { user: "test" },
success: function(json) {
console.log("login successful");
}
});
Related
I'm trying to use the BloomAPI to retrieve Doctor's NPI number by querying with their first and last name. I'm using Jquery Ajax to make a get request for the JSON data.
I am able to get the JSON data when I do CURL in the terminal: curl -X GET 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN'
For the purpose below - I just hardcoded in the params into the URL.
I get a "Failed to load resource: the server responded with a status of 400 (Bad Request" Error. Any idea what I might be doing wrong?
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp'
}).done(function(server_data) {
console.log(server_data)
}).fail(console.log("failed"));
This was a weird one... your code is actually basically correct, however, it appears bloomapi does not support disabling caching in the way jquery does it.
When you make the jquery call you have, the actual url becomes something like this:
http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN&callback=jQuery111207365460020955652_1428455335256&_=1428455335257
The callback is a jsonp construct, and the _ is a way of breaking caching. However, bloomapi appears to not like this:
jQuery111207365460020955652_1428455335256({"name":"ParameterError","message":"_ are unknown parameters","parameters":{"_":"is an unknown parameter"}});
To get around this, you can disable cache busting like so:
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp',
cache: true
}).done(function(server_data) {
console.log(server_data)
}).fail(function() { console.log("failed") });
You will have to be careful of how else you break the cache if that's an issue; the api provider may be able to provide feedback on how to do this.
In the future, you can easily check the errors you are receiving/what you are sending using a web debugger; I used Fiddler to figure this out.
So I have to send some data to a php page, and it will return me another php page based on my data.
I send the data this way:
$(document).ready(function() {
$.ajax({
url: '//www.example.com/page.php',
type: "post",
dataType: 'jsonp',
data: { myvar:myvalue },
success: function(response) { console.log("success."); },
error: function(XMLHttpRequest, textStatus, errorThrown) { console.log("error."); },
complete: function() { console.log("complete."); }
});
});
It shows an alert saying jQuery180014405992737595236_1357861668479 was not called (numbers are copied from other question)
I think the reason is that it's expecting a json result from the page, when it's not.
In Chrome it says Uncaught SyntaxError: Unexpected token < referring to the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
To sum up, this works, but that jQuery alert and the console error needs to be fixed, and I think the right way would be handling properly the returned result page.
I hope you guys can help me fix it that seems quite a simple task, but Im really new to this. Thanks
Removing the dataType: 'jsonp' or changing it to 'json' turns out on my script not being executed and getting the following error:
XMLHttpRequest cannot load http://www.example.com/page.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com/myPage' is therefore not allowed access.
I think the reason is that it's expecting a json result from the page
It's expecting a JSONP response. (JSONP is not JSON). You said:
dataType: 'jsonp',
… which explicitly forces jQuery to treat the response as JSONP (and, as a side effect, GET).
the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
The server shouldn't be returning a PHP page. It should be executing the PHP code and returning whatever that outputs. It looks like it is outputting HTML.
You need to either:
Not tell your script to expect JSONP. (Note that you'll probably then have to configure CORS on the server to deal with same origin issues) or
Change the PHP to return JSONP
I want to execute the following AJAX call (cross domain):
$.ajax({
type: 'GET',
url: url + "?callback=?",
contentType: 'application/json',
async: false,
jsonp: "callback",
dataType: 'jsonp',
success: function (json) {
alert("ok" + JSON.stringify(json));
},
error: function (json) {
alert("err" + JSON.stringify(json));
}
});
And I am getting this alert message:
err{"readyState":4,"status":200,"statusText":"success"}
Which means the code ends in the error method.
If I check the request in Firefox or Chrome, the JSON part of the response is available and clearly formatted. Is it possible to get the JSON response in the error method? Or do you have any idea why the success method isn't hit?
It's not my server unfortunately, so I can't implement any changes on the server side. I used http://jsonlint.com/ to validate the JSON output and it is Valid. Entering the same URL in the browser returns the JSON content correctly.
Thanks much in advance,
I tried a few different approaches, but still failing on the error method,
[EDIT]
SO, I am playing with different approaches, always getting the same error. If I change the error part of my call to this:
error: function (jqXHR, textStatus, ex) {
console.log(arguments);
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
Then I am getting the following error:
http://i.stack.imgur.com/ck6Sd.png
Copy paste of error for search engines:
0: Object
1: "parsererror"
2: Error
message: "jQuery11020553141210693866_1392367304225 was not called"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
proto: d
callee: function (jqXHR, textStatus, ex) {
length: 3
proto: Object
The same things apply as above, the response is readable in the browser without issues.
EDIT2
I ended up doing the JSON call the old way, embedding it into the page:
script = document.createElement("script");
script.type = "text/javascript";
script.id = "resultJSON";
script.src = url;
$(".resultsOutput").append(script);
But I have troubles retrieving the data, the script tag seems to be empty. I am getting an error on the JSON:
Uncaught SyntaxError: Unexpected token :
Anyone able to help? I am starting to get desperate on this one. It seems that the issue is that the JASON is returned without a method wrapper.
[LAST EDIT]
So, turns out the server doesn't support CORS and the returned JSON isn't wrapped in a JS function, so this approach won't work. I'll have to use some other approach to retrieve the data.. thanks everyone for reading
Andy
Is there any particular reason to:
Override random callback name jquery gives?
Set datatype to application/json?
This second one may be causing the error. If I'm correct, the server would return application/javascript mime-type, since it should return the JSON you are looking for wrapped into a callback function that shall be called once the request hast completed. Something like this:
function callback() {
return {"a","b"} //the JSON you are looking for
}
This all is handled internally by creating a tag "script" to avoid cross-domain browser restrictions, so you cannot handle JSON directly, it needs to be wrapped into Javascript code. Thus, contentType may be wrong.
Try removing the contenType property on the ajax options and see how jquery behaves (it should interpret content-type from response headers from the server).
I know this question has been asked, but I cannot get it working.
I execute the following AJAX request:
function dislikeMeme(memeId) {
$.ajax({
dataType: "jsonp",
url: "http://<url>.com/dislike/" + memeId,
data: {
u: "username",
p: "password"
},
jsonpCallback: 'successCallback'
});
}
function successCallback(data) {
alert("Test"); // Not firing because of previous 'Invalid label' error
};
Looking at firebug I see that the request was successful, but there is an Invalid Label error which fires the Error callback of the request. The response of the request is as follows:
{
"id":6220673,
"myScore":-1,
"msg":"Not loved"
}
I see that the parentheses are causing JavaScript to interpret the response as an object, but I know this is the format I am retrieving, isn't there anyway to parse this before it causes an error?
I also see that the URL of the page returning this information is:
http://<url>.com/dislike/123456?callback=successCallback&u=username&p=password&_123456789
Everything is working perfectly except this Invalid label error. Does anyone have any ideas?
Thanks in advance everyone
A server that can handle JSONP takes the callback paramater (can be different parameter depending on WS) and passes it in the response. So the response from the server should be:
successCallback({
"id":6220673,
"myScore":-1,
"msg":"Not loved"
})
If you don't have control over the server your only route is proxy. See my cross domain answer for information on getting around same origin policy.
What prevents me from using $.ajax to load another domain's html?
With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.