"Invalid label" when calling jsonip.com with jQuery with jsonp - javascript

I'm going absolutely crazy... I keep getting an "invalid label" error in Firebug when executing this simple piece of Javascript:
$(document).ready(function(){
$.ajax({
url: "http://jsonip.com",
dataType: "jsonp",
success: function(data) {
alert("success!")
}
});
});
Firebug will say (in the console tab):
Invalid label
{"ip":"99.99.99.99"}
with a pointer to the first double quotes (IP address mocked for obvious reasons).
The call in in the net tab is what one would expect: http://jsonip.com/?callback=jQuery17108684927028894522_1326752040735&_=1326752042159, so the callback parameter is in place too.
I'm using jQuery 1.7.1. I have also tried this with jQuery 1.6.4 but without success.
Anyone...? Thanks!

To specify a JSONP callback to jsonip.com you must to put the callback name like this:
http://jsonip.com/{theCallback}
To do this with jQuery, there are some simple configurations to the ajax method. This code works for me:
$(document).ready(function() {
$.ajax({
url: "http://jsonip.com/theCallbackFunction",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "theCallbackFunction",
success: function(data) {
alert(data.ip);
}
});
});
Regards!

The callback function seems to be passed as a url fragment. Check the fiddle

Regarding to the answer by eagleoneraptor and the comment by lonesomeday:
You may create a dynamic name for the callback-function on the fly and append that name to the url:
$.ajax({
url: "http://jsonip.com/",
dataType: "jsonp",
jsonpCallback:function(){var fnc='cb'+$.now();this.url+=fnc;return fnc;},
jsonp:false,
success: function(data) {
alert(data.ip)
}
});
http://jsfiddle.net/doktormolle/YfHYs/

I run jsonip.com.
The service now supports:
CORS
path callbacks, http://jsonip.com/myfunc => myfunc({"ip":""})
parameter callbacks, http://jsonip.com/?callback=myfunc => myfunc({"ip":""})
Note that for the parameter callbacks, ?callback is required. "myfunc" can, of course, be whatever you want.
See http://jsonip.com/about for details.

Related

Getting json on cross domain with jsonp using jquery

I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc

Uncaught TypeError: number is not a function when parsing JSONP response in jQuery ajax call

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

Extract and read JSON Data from web API

What I'm working on is providing 1 line instant definitions of terms and perhaps one line answers to few logical questions. Suppose a user inputs "JavaScript" and JavaScript visits the url https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1, gets the item "Definition" (Look at the API link to understand, Definition is in the first line itself) and displays its value of Definition and alert the user with the required data.
Anyways my code currently is:
<html>
<head>
<title>Hi</title></head>
<body>
<input id="ddgAPI"><button>Search</button>
<div id="output"></div>
</body>
</html>
Please note that I've not put in the required JavaScript/jQuery code as I'm confused with this. Thank you :)
Because this is a cross-domain request you can only do this with a proxy or with JSONP. Fortunately DuckDuckGo supports JSONP, so you just need to ensure that you add a callback parameter to the URL request like:
https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1&callback=jsonp
... or use the appropriate jsonp parameter with jQuery's ajax method, something like:
$('#ddgAPI').on('keyup', function(e) {
if (e.which === '13') {
$.ajax({
type: 'GET',
url: 'https://api.duckduckgo.com/',
data: { q: $(this).val(), format: 'json', pretty: 1 },
jsonpCallback: 'jsonp',
dataType: 'jsonp'
}).then(function (data) {
console.log(data);
});
}
});
Use jQuery.ajax() to talk to the remote service. url should be https://api.duckduckgo.com. type should be GET. data should be:
var data = { q:'JavaScript', format:'json', pretty:1 };
jQuery will then compile everything into an AJAX request, send it to the server. Pass a function as success so you can do something with the result:
$.ajax({
url: "https://api.duckduckgo.com",
type: "GET",
data: { q:'JavaScript', format:'json', pretty:1 },
success: function(data) { $('#output').html(data); }
});

How to get request url in a jQuery $.get/ajax request

I have the following code:
$.get('http://www.example.org', {a:1,b:2,c:3}, function(xml) {}, 'xml');
Is there a way to fetch the url used to make the request after the request has been made (in the callback or otherwise)?
I want the output:
http://www.example.org?a=1&b=2&c=3
I can't get it to work on $.get() because it has no complete event.
I suggest to use $.ajax() like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
craz demo
Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
So you would use
$.ajax('http://www.example.org', {
dataType: 'xml',
data: {'a':1,'b':2,'c':3},
context: {
url: 'http://www.example.org'
}
}).done(function(xml) {alert(this.url});

A quick question on data returned by jquery.ajax() call (EDITED)

EDIT: The original problem was due a stupid syntax mistake somewhere else, whicj I fixed. I have a new problem though, as described below
I have the following jquery.ajax call:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
dataType: "xml",
success : createTaskListTable
});
The createTaskListTable function is defined as
function createTaskListTable(taskListXml) {
$(taskListXml).find("Task").each(function(){
alert("Found task")
}); // each task
}
Problem is: this doesn't work, I get an error saying taskListXml is not defined. JQuery documentation states that the success functions gets passed three arguments, the first of which is the data.
How can I pass the data returned by .ajax() to my function with a variable name of my own choosing.
My problem now is that I'm getting the XML from a previous ajax call! How is this even possible? That previous function is defined as function convertServiceXmlDataToTable(xml), so they don't use the same variable name.
Utterly confused. Is this some caching issue? If so, how can I clear the browser cache to get rid of the earlier XML?
Thanks!
See my comment. If you're using IE, GET AJAX requests are cached. jQuery can solve this for you by adding a random querystring variable to the request. Simply change your AJAX call to this:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
cache: false,
dataType: "xml",
success : createTaskListTable
});
That will add the random querystring automatically, thus preventing the browser from caching the request.
Try defining your callback inline like this:
success: function createTaskListTable(data, textStatus, xhr) {
console.dir(data, textStatus, xhr);
}
If data is indeed being returned as null, you might get some insight from the other fields, especially xhr.
Note that error callbacks get called with (xhr, textStatus, errorThrown).

Categories

Resources