Get JSONPto work - javascript

I am trying to access data from a php server with a cross domain support. So when i try $.ajax with dataType : 'jsonp' i have an error in console: Uncaught SyntaxError: Unexpected token The file is interpret as a javascript file an the request fail. Have you an idea for get data whithout this error.
$.ajax({
url : 'http://domaine.com/json.php',
contentType: "application/json; charset=utf-8",
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});

First make sure that your PHP script supports JSONP. Identify the query string parameter that needs to be passed so that the script returns JSONP. Then test it in your browser by directly entering the following address in your address bar:
http://domain.com/json.php?callback=abc
You should see something along the lines of:
abc({ ... some JSON here ... })
You might need to adjust the callback name parameter if your PHP script expects a different one. This could be the case if you see the following output ({ ... some JSON here ... } without being wrapped in your javascript function)
And once you have ensured that you have a valid PHP script that returns JSONP you could consume it:
$.ajax({
url : 'http://domain.com/json.php',
jsonp: 'callback',
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
Things to notice:
I have specified the callback using the jsonp: 'callback' parameter
I have gotten rid of the contentType: 'application/json' parameter because jQuery's implementation of JSONP uses script tags which doesn't allow you to set any request headers.

You need to add ?callback=? to the request so that the proper callback is evaluated. It may not be called callback, though. You need to find out what it is called from the domain.
If the domain (and browser) supports CORS, you don't even need to use JSONP. You can use a normal request.

Related

jQuery ignores HTTP request method and appends weird URL parameters

I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.

AJAX with JSONP returns error Callback is Undefined

Here is my ajax call. I know the headers are correct because when I access the url directly it gives me something like this: jsonpCallback({"id":"274"})
But when I make the ajax call - it is saying Uncaught ReferenceError: jsonpCallback is not defined
$.ajax({
url: 'http://localhost:9000/product/rest/company?' + $('form').serialize(),
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
jsonpCallback: 'callback',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
}).then(function(data) {
console.log(data);
});
What am I doing wrong in this call?
The server is giving back the JSONP resource using the wrong callback function name.
You wrote that the response from the server is something like:
jsonpCallback({"id":"274"})
The JSON data is wrapped into the padding function jsonpCallback whose name is not matching with the parameter specified in the Ajax request. It should be:
callback({"id":"274"})
in fact callback is the name passed as jsonpCallback option in the jQuery AJAX call
jsonpCallback: 'callback',
Editing the server side script that generates the response to apply a proper callback name will fix things.
Alternatively you can fix things on "the other side" by making the ajax call parameter matching with the function name in the response:
jsonpCallback: 'jsonpCallback',
The above is the "quick fix".
However it is strongly reccomended that you don't specify a custom callback name (using the parameter jsonpCallback).
Instead let jQuery generate a random callback name for each request.
The server side script will then parse the GET parameter callback and use the name passed for the callback function name that wraps the JSON data.
For example if you make a request like:
http://localhost:9000/product/rest/company?param=123
jQuery will add a parameter to the query string like this:
http://localhost:9000/product/rest/company?param=123&callback=jQuery1520422276
(it actually uses a longer callback name)
The server should parse callback and build up the response using the value passed as the padding function that wraps the JSON returned data:
jQuery1520422276({"id":"274"})

Uncaught SyntaxError: Unexpected token : - data still coming through

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

Script5007 error "object not found" only on Internet Explorer

When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.

How do I pass or parse that access_token from the Dom to a Variable I can then Store and call for access_token?

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.

Categories