jquery jsonp request is not getting a callback parameter added properly - javascript

I have an object containing UPC codes and I'm iterating through them, hitting a server for product info on each via jsonp requests:
$.each( obj, function( key, val ){
var requestUrl = 'https://domain.com/products/' + val.upcCode + '/prices';
$.ajax({
url : requestUrl,
dataType : 'jsonp',
success : function(responseData){
console.log( responseData );
}
});
});
This works except for that the first request is not getting a callback parameter added properly. All the other requests get
&callback=jQuery111108732157719514818_1411587984724&_=1411587984725
(or similar) appended but the first is only getting
&true=jsonp&_=1411587984723
So the server doesn't get a callback and just returns json. Has anybody seen jQuery doing this?

The answer appears to be that I had made a separate, earlier jsonp request wherein I manually set the jsonpCallback value to 'jsonp':
$.ajax({
url : '/logic/under29.js',
dataType : 'jsonp',
jsonpCallback : 'jsonp',
success : function(response){
console.log( response);
logic = response;
}
});
Name that callback anything else and the second jsonp request works. Name it "jsonp" and you get the problem described above.
(jquery 1.11.1)

Related

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

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

Function returns JSONP. How to display as JSON - Javascript/jQuery

I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}

Get JSONPto work

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.

jQuery cannot get a success function working

I am having trouble getting a success: function(){} working - the ajax code I am using is this:
jQuery.ajax({
url: 'http://127.0.1/process_form.php'+data,
data: data,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback"
});
data is a simple string and is being passed by jsonp as when complete will pass data cross domains. I know about security with a GET and that Curl would be better, but this is a simple "predefined" string with no user input. The data is just the text from one of 4 links. i.e. "yes" "No" "Don't know" "made this one up" There is actually no need for a form either.
I get all the "data" into the DB but what I can't get to happen is the "next" bit based on the success. If I do a simple success: function(){} nothing happens (with that function) regardless of "what" e.g. an alert etc.
What should (and does of sorts) happen is the data is posted to the DB, a jQuery.getJSON statement then queries the DB and prints out ALL the data i.e. all entered rows, not just the last.
When I say "sort of works" the jQuery.getJSON returns the data, but sometimes "misses" doing it until the next time data is sent. It seems to me all to do with timing because if I wrap the "print" function inside a setInterval() the whole thing works fine. Just I don't really need the setInterval to contunually work.
For example:
jQuery('.addinput').live('click',function(){
var fldID = new Date().getTime();
var fldType = jQuery(this).html().toLowerCase();
var data ='';
data += '?fldID='+fldID;
data += '&fldType='+fldType;
data += iptime;
jQuery.ajax({
url: 'http://127.0.1/process_form.php'+data,
data: data,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback"
});
jQuery('.loader').fadeIn('slow');
setInterval(function() { fn_form(iptime); }, 3000 );
jQuery('.loader').fadeOut('slow');
return true;
});
This works OK but I really don't want the fn_form(iptime) function to be continually refreshed.
What I'd rather see is something like this:
jQuery('.addinput').live('click',function(){
var fldID = new Date().getTime();
var fldType = jQuery(this).html().toLowerCase();
var data ='';
data += '?fldID='+fldID;
data += '&fldType='+fldType;
data += iptime;
jQuery.ajax({
url: 'http://127.0.1/process_form.php'+data,
data: data,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(){
// run fn_form(iptime)
}
});
You can use this alternative solution to jQuery's implementation of JSONP which simplify JSONP calls.
jQuery-JSONP features:
1- error recovery in case of network failure or ill-formed JSON responses,
2- precise control over callback naming and how it is transmitted in the URL,
3- multiple requests with the same callback name running concurrently,
4- two caching mechanisms (browser-based and page based),
5- the possibility to manually abort the request just like any other AJAX request,
a timeout mechanism.

Categories