$.ajax(
{
url : "http://search.twitter.com/search.json?q=google&lang=en&rpp=10&since_id=&callback=?",
dataType : 'json',
success : function(data)
{
alert(data.results.length);
}
});
How exactly is this working ? I mean the cross-domain request.
jQuery detects the callback=? part of your URL and automatically switches the dataType from 'json' to 'jsonp'.
JSONP is a JSON query that is not made using XMLHttpRequest but by adding a script tag to your page. Calling back into your script is handled by the caller giving the name of a JavaScript function to execute when the script loads. This is why cross-domain is working.
jQuery will handle JSONP transparently for you in a $.ajax request. The manual (and to me cleaner) way to do this is to define a 'jsonp' dataType and use the placeholder ? for the callback name in the URL. jQuery will automatically replace the ? with an appropriate value to trigger your success callback.
$.ajax(
{
url : "http://api.twitter.com/1/users/show/google.json&jsoncallback=?",
dataType : 'jsonp',
success : function(data)
{
alert(data.results.length);
}
});
jQuery defines your callback function in the global scope, then substitutes callback=? in the URL with callback=nameItGaveTheFunction.
It then functions as a normal JSONP request; using script tags, and wrapping the response in the callback function.
I believe that jQuery realises it's cross domain and so adds a script tag to the page header with the appropriate src attribute (rather than firing of an ajax request). This loads the JSON and then fires the callback.
Related
I'm trying to load html content cross-domain using ajax. Here is my code:
$.ajax({
crossDomain: true,
crossOrigin: true,
url: 'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
type: "GET",
dataType: "JSONP",
success: function (data) {
$("#divTest").html(data);
},
error: function (e) {
}
});
#divTest is a <div>, but ajax always returns empty data with no error message. I tried setting crossOrigin, crossDomain properties as suggested, but without success. Can someone look and let me know what I'm missing ?
Also: is there any better and secure way to load html content cross-domain?
Update: After implementing the latest jQuery, it gets status code 200 and thinks of it as success.
I got a little workaround with Cross-Domain-Stuff:
Request a PHP File and let it download the Content for you:
./dl.php?url=http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Because Webpages give out there Content, but don't like it Framed or by Ajax.
The PHP Script is as simple as:
<?=file_get_contents($_GET["URL"]); ?>
Of course you may add to this, but it'll work too.
Did you tried with getJSON method of jquery Ajax, here are some examples
But your server should also allow cross domain
I am trying to make a simple ajax request(cross-domain) using Json.
Here's my code :
$("#unsub").live('click', function() {
$.ajax({
url: urly ,
type:'GET',
dataType:"json", //type JSON
success: function(data) { //do something
}
});
});
However, the response I am getting from the server is a html Div
<div id="handler"></div>
On button click I get an error on success "XML can't be the whole program".
Please note : i have to USE json to make the call no matter what and the call will always return a div. using jquery 1.3.2
Any help would be highly appreciated.
Thanks for the time.
Most of the time you need to provide the remote server a "callback" in url for the jsonp to be wrapped in. If API is not set up for JSONP, you need to use other methods to egt the JSOn with javascript. First check that API will deliver jsonp, and if so what params to put in the url
This is rather a syntax question I am going to explain it jQuery's ajax functionality.
Let's say I want to control dataType of all ajax request according to url. For example url's with parameter &parseJSON=true should have a dataType of 'JSON' automatically.
For example:
$.myajax({url:'http://example.com&parseJSON=true'})
should be equivalent to
$.ajax({url:'http://example.com&parseJSON=true', dataType: 'JSON'})
Basically, I need to check for URL and add dataType parameter if needed.
Thanks
I think you can do this with a prefilter:
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
// Modify options
if ( !options.dataType && /parseJSON=true/.test(options.url) ) {
return "json";
}
});
I don't have an environment to test this at the moment.
Edit: Just to clarify, you would use ajax requests just like you do now, with $.get, $.post, and $.ajax, you just don't have to supply a dataType anymore.
Why does this not work? anybody:
In my code I have:
$.getJSON("http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=?",
function(data){
//This never gets executed
alert('here');
});
The text file can be viewed here:
http://isp123.co.uk/cw/NorthWales/Test.txt
This is not a JSONP response:
({"name" : "hello world"});
If you had a proper JSONP response, then your code should work.
The question mark in the "callback=?" part of the URL is changed by jQuery before making the request, your JSONP server needs to be able to dynamically create the JSONP "function" in response to the unique jQuery request. If you can't dynamically create your JSONP, perhaps you could use YQL/Yahoo pipes to turn it into JSONP?
This pipe should do the trick, to see if it works, use this URL instead in your getJSON function: http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?
I just tried this and it worked:
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?", function(data){
//This always gets executed!!!
alert('here');
});
I don't know if you know enough about JSONP but this is not JSONP
?({"name" : "hello world"});
It really should be something like this http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=foo
foo({"name" : "hello world"});
From the jQuery.getJson manual page:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
Your JSON is invalid according to http://jsonlint.com/
Here Clearly mentioned
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
and read jsonpCallback section
jsonpCallback,
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
Probably worth using jQuery.ajax() - http://api.jquery.com/jQuery.ajax/
You can pass in the dataType as "jsonp" and then jQuery takes care of all the callback business, but more importantly you can specify a function to run when there's an error, which may help you:
$.ajax({
dataType: "jsonp",
success: function(d) {console.log(d);},
error: function() { console.log("error") } //do your debugging in here
//add other parameters such as URL, etc
});
The error function you define can be passed 3 variables, read up on it on the ajax() page on the jQuery docs (linked at the beginning of my post) to find out more about that and how to use them.
Your problem lies with how your server is outputting the information. In the link you've supplied, the assumption is that any name placed in the ?jsonpcallback should result in wrapping the JSONP code in a function with that same name. It, however, is not the case.
So the next option is this: use a static function name in your server file and wrap the code. (e.g. use foo(<jsonp>) and stick with it) Then, you have to explicitly tell jQuery that we are going to use a specific function name (leave jQuery with the assumption it's supplying (and thus receiving) that name back, when in-fact you're just supplying it server side and filling in the blanks).
Once you have your file setup, use something like the following:
$.ajax({
// setup the request
url: 'http://isp123.co.uk/cw/NorthWales/Test.txt',
crossDomain: true,
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'foo', // "supply" the jsonp function (pseudo-defined)
// function to call when completed
complete: function(data){
alert(data);
}
// just in case, catch the error
error: function(j,t,e){
alert('AJAX Error');
}
});
So now when jQuery makes the call and it thinks it's supplying the callback, it's really just getting the server-defined callback in return. So, for the above to work, your text file should look something like this:
foo({name:"Hello, World!"});
Also, if you can, change your header to application/javascript, though this is some-what optional.
I'm having trouble pulling a specific element from an API call using jQuery's getJSON function. I'm trying to use SunlightLab's congress API to pull specific info about legislators. In the example below I'm trying to pull a legislator's website:
$.getJSON("http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]&lastname=Weiner&jsonp=?" , function(data) {
alert("hello from sunlight");
alert(data.response.legislator.website);
});
Using the above code, the first alert shows up but the second alert does not even occur. I understand that getJSON should be using JSONP in this instance, and I think I have that set up correctly, ending my URL with '&jsonp=?'.
Putting the URL in my getJSON function into a web browser gives me this:
?({"response": {"legislator":
{"website":
"http://weiner.house.gov/", "fax":
"202-226-7253", ... etc.
I'm a little thrown by the '?' showing up at the beginning of this, but if the first alert is showing up then the request must be succeeding...
The URL you're using is setting the JSONP callback to be equal to ?, which means its injecting a JavaScript function called ? with an argument of a JavaScript object. This is invalid. So, the request is succeeding, but the wrapper function you've defined isn't being called (and isn't valid).
You could change the URL so that its jsonp=callback (or some other handler function name), and then define a function called callback that handles an argument that expects the object.
One way to (automatically) trigger JSONP support in jQuery is to switch the key to be called 'callback' so that it signals to jQuery that you're doing a JSONP call. ie, callback=callback.
EDIT: As Drackir points out, jQuery provides a setting in $.ajax for letting it define it's own callback function name, but you need to signal to it that its a JSONP call by setting dataType: 'jsonp' in the $.ajax call.
The question mark is there because you specified the JSONP callback function to be ? in your query string (ie. &jsonp=?). Due to security concerns (specifically the same-origin policy) you cannot do an AJAX request to a site outside the same domain as the page you're on. To get around this, JSONP works by creating a script tag, with the SRC set to the URL of the script on the other site. This will load the external JavaScript file and run whatever code is there. Now, in order to link that external code with your JavaScript, the external API takes the name of a function to call (&jsonp=functionnametocall). The returned JavaScript calls that function and passes in the data it's trying to return as a JSON object as the first argument.
So, the reason you see the question mark when you go there is because you're passing a question mark to the jsonp query string parameter. jQuery will automatically convert the question mark in a url such as http://www.test.com/api/apikey=292929&callback=? to a uniquely named function. This is handled in the background by jQuery so you don't have to think about it.
Now, that said, I don't know if jQuery detects if the name of the callback parameter as being something other than callback=?. $.getJSON() however is a short form for the longer:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
I suggest you try using $.ajax() directly and set the jsonp setting equal to "jsonp". This tells the $.ajax() method that the query string parameter is called jsonp and not callback. So like this essentially:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
jsonp:"jsonp"
});
More information: $.getJSON | $.ajax()
OK, OK, so it was a rather simple fix, adding a line to the the example given by #Drackir. The missing piece was 'cache: true' within the ajax settings. The final working code looked like this:
$.ajax({
url: 'http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]7&lastname=Weiner',
dataType: 'jsonp',
cache: true,
jsonp: 'jsonp',
success: function(data) {
alert("hello from ajax") ;
alert(data.response.legislator.website);
}
});
I'm not sure why 'cache: true' is needed in this case. Thanks for the help.