Getting json on cross domain with jsonp using jquery - javascript

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

Related

Taking data out of the Ajax Jsonp

I want to taking data out of the Ajax Jsonp.
Why doesn't work this app?
Please Help.
var res;
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
}
});
$("div").html(res);
https://jsfiddle.net/q6vfgemp/
The data is retrieved correctly but since the request is async you cannot set the html outside of the success callback, put it inside the success callback and it will work.
Also it's a good practice to console.log the data when you're not sure where the problem is to make sure it is retrieved successfully.
Edit: Here is why the async: false option is not working, check the accepted answer for the details.
In JSONP you should add a callback parameter to the request.
The response would be a script calling your callback with the requested data.
So, you should call a URL like this:
http://domain.ext/?callback=xxx
And you should have a function with name "xxx":
function xxx(data) {
// Here you can manage the received data
}
Also, the requested resource should support JSONP, if it doesn't you will not receive anything in your callback.
Since the request is asynchronous, your code sets the "div" before the result is actually retrieved. In order to make sure you retrieve the result, and then set the div, do this:
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
$("div").html(res);
}
});

.ajax returning json object, but no success

I am using JQuery's .ajax method to call to a URL which returns a JSON encoded string. I can see the object returned from the GET in the debugger, but for some reason I'm not falling into the success function. Any ideas?
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
If you look at the documentation, it shows that the proper way to make a jsonp request requires a jsonCallback parameter.
Code:
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie&jsonCallback=?',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
Fiddle: http://jsfiddle.net/xrk4z6ur/2/
jQuery will by default use callback=? for a jsonp request. In this case, the API accepts jsonCallback. Adding jsonCallback=? to the url will let jQuery handle it properly.
If you are using jsonp you should specify a callback GET parameter like &callback?
On server side return the callback with your desired data as argument (json encoded)

AJAX .responseText want to assign to global variable

For CORS AJAX request, the best and cross browser supported example is the following one as I know...
http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/
The above one working as properly but callback return only local variable not global. Can somebody give me the idea how to make global variable return from AJAX callback.
In jQuery code, if I would like to return global variable result I can do as follow:
jQuery.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: url,
success: function(data){
result = data;
},
error: function(xhr){
alert("Request cannot complete");
},
async: false
}).responseText;
But above jQuery.ajax() POST example is not fully support by IE.

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

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.

Jquery Ajax Problem

Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?
In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.
To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});

Categories

Resources