I can’t just use .load() because I’m building a custom loading bar that’s actually truthful about the percentage that has currently been loaded (yes that’s actually possible): http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/
I’ve got the loading bar working now but I need to replicate the following jQuery functionality inside the .ajax() function so I can append the #ajaxContent stuff to the .ajaxContainer div once it’s finished loading:
$('.ajaxContainer').load('/path/to/file.php #ajaxContent')
The equivalent would be:
$.ajax('/path/to/file.php'/*,{extra: settings}*/).done(function (response) {
$('.ajaxContainer').html($("<div>").append( $.parseHTML( response ) ).find( '#ajaxContent' ));
});
I think is quite simple to provide a simple answer, I prefer to illustrate you the procedure for retrieve yourself.
If you read the docs of .load() on jQuery site you read:
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success)
If you read the docs about .get() you read:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
Where dataType
dataType Type: String The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, or html).
So in your case you must fill the html element with data from success callback like this:
$('.ajaxContainer').html(response);
Related
If I wish to fetch data from a remote server, then JSONP is the tool of choice I believe. But I am confused by an example I have seen:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
dataType: 'jsonp',
data: 'p3=c',
jsonp: 'callback',
url: 'http://someserver.com/app?p1=a&p2=b',
success: function (data) {
console.log("data="+data);
$.each(data, function (i, r) {
console.log("i="+i);
console.log("r="+r);
});
},
});
});
</script>
I can see that in the request, a callback parameter has been added with value in the format jQuery1234567890. When I look at the app that processes that request, it extracts the callback parameter from the request and wraps the json data to be returned with that and relevant brackets, so it ends up returning something like this:
jQuery1234567890([{"x":"100","y":"101"},{"x":"200","y":"201"}])
So my first questions are:
(1) Is the app correct to have done what it has?
(2) What has jQuery / JSONP actually done for us?
I was assuming that jQuery would see the dataType of "jsonp", insert a script tag into the DOM, the browser would then download and execute the script. If that's right, has jQuery created the function jQuery1234567890, the implementation of which is to pass the parameter on to the success function?
(3) Is my understanding correct (I don't think it is)?
Thank you,
Paul
(1) Is the app correct to have done what it has?
Yes, that's a correct JSONP format
(2) What has jQuery / JSONP actually done for us?
Notified the server application that JSONP is desired by placing a &callback=jQuery1234567890 in the request
I was assuming that jQuery would see the dataType of "jsonp", insert a script tag into the DOM, the browser would then download and execute the script. If that's right, has jQuery created the function jQuery1234567890, the implementation of which is to pass the parameter on to the success function?
(3) Is my understanding correct (I don't think it is)?
Yes, your understanding is correct. It has created a script with a jQuery1234567890 function which is invoked when the requested scripted is loaded. And as you stated the parameter receives the data and passes it on to the $.ajax internals, which invokes the success callback
From the ajax docs for the jsonp option:
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.
So using jsonp: 'callback' overrides callback with callback, essentially doing nothing.
The other stuff you're seeing is generated by jQuery so that you don't have to do it yourself. You get to simply treat this request like any other ajax request in jquery and not worry about the implementation of the jsonp.
I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});
I want to get live currency rates from an external source, so I found this great webservice:
Currency Convertor
This service is working like a charm, the only downside is that it does not provide JSONP results, only XML. Therefore we have a cross browser problem while trying to consume this webservice using jQuery $.ajax().
So I found Yahoo Query Language which returns results as JSONP and also mangae to consume other webservices and return me the results. This is also working, here is an example URL:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.webservicex.net%2FCurrencyConvertor.asmx%2FConversionRate%3FFromCurrency%3DNOK%26ToCurrency%3DEUR'&format=json&diagnostics=true&callback=cbfunc
This URL return JSONP result and is working like a charm, but the problem appears when I use this in my code:
$.ajax({
type: "GET",
url: urlToWebservice,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
$("#status").html("OK: " + data.text);
},
error: function(xhr, textStatus, errorThrown) {
$("#status").html("Unavailable: " + textStatus);
}
});
When I try to run this code nothing happens, and I can see this error message in my Firebug javascript debugger:
cbfunc is not defined
cbfunc is the name of the container which surrounds the JSON response, but why does it say not defined?
EDIT:
This is my new code, but I still get the cbfunc is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.webservicex.net%2FCurrencyConvertor.asmx%2FConversionRate%3FFromCurrency%3DNOK%26ToCurrency%3DEUR'&format=json&callback=cbfunc",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc'
});
function cbfunc(data) {
alert("OK");
}
And the "OK" message is never fired...
If available, use the jsonpCallback parameter in the call to $.ajax like:
jsonpCallback: "cbfunc",
Its description, from the jQuery API docs reads:
Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery.
The docs later go on to say:
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.
However it is not advised to make use of this "preferable" behaviour when making use of YQL. Precisely why that approach is not ideal might make this answer far too verbose, so here is a link (from the YQL blog) detailing the problems with jQuery's preferred approach, making use of jsonpCallback and so on: Avoiding rate limits and getting banned in YQL and Pipes: Caching is your friend
You should let jQuery handle the callback by changing urlToWebservice to end in callback=?
The reason it's not working is because by specifying callback=cbfunc in the querystring generates a URL of the type:
http://query.yahooapis.com/...&callback=cbfunc&callback=jsonp1277417828303
Stripped out all uninteresting parts, but the URL contains two callback parameters. One of them is managed by jQuery, and the other one not. YQL only looks at the first callback parameter and returns a response wrapped around that.
cbfunc({"query":{...}});
However, there is no function named cbfunc in your script, so that's why you are getting the undefined error. jQuery created an implicit function named jsonp1277417828303 in the above example, and the response from YQL should instead have been:
jsonp1277417828303({"query":{...}});
for jQuery to act upon it, and return the response to your success callback which it never got to do.
So, as #SLaks suggested, remove the &callback=cbfuncfrom your URL, or replace it with &callback=? to let jQuery handle things.
See a working example.
You definitely should give jQuery-JSONP a try: http://code.google.com/p/jquery-jsonp/
Simplifies everything :)
Im trying out the new graph api for facebook. I'm trying to fetch some data using jquery ajax.
This is a sample of my javascript code, very basic...
var mUrl = 'https://graph.facebook.com/19292868552';
$.ajax({
url: mUrl,
dataType: 'json',
success: function(data, status) {
$('#test').html(data);
alert(data);
},
error: function(data, e1, e2) {
$('#hello').html(e1);
}
});
The url is to a page that does not need access tokens (try it using a browser), but the success function returns an empty object or null.
What am I doing wrong? Thankful for all help!
I have covered this and asked this question before. I made a quick tutorial which covers exactly this and explains it all.
In short:
JSON is not made for cross domain usage according to its same-origin policy. However the work around is to use JSONP which we can do in jQuery using the supported callback parameter in facebook's graph api. We can do so by adding the parameter onto your url like
https://graph.facebook.com/19292868552?callback=?
by using the callback=? jQuery automatically changes the ? to wrap the json in a function call which then allows jQuery to parse the data successfully.
Also try using $.getJSON method.
I was trying to do something similar, in testing I was able to get a working result which I saved on jsFiddle: http://jsfiddle.net/8R7J8/1/
Script:
var facebookGraphURL = 'https://graph.facebook.com/19292868552';
$.ajax({
url: facebookGraphURL,
dataType: 'json',
success: function(data, status) {
$( '#output' ).html('Username: ' + data.username);
},
error: function(data, e1, e2) {
$( '#output' ).html(e2);
}
})
HTML:
<html>
<body>
<div id="output">BorkBorkBork</div>
</body>
</html>
Hope that helps! :)
...The Graph API supports JSONP. Simply pass callback=methodname as an extra parameter and the returned content will be wrapped in a function call, allowing you to use a dynamically inserted script tag to grab that data.
http://forum.developers.facebook.com/viewtopic.php?pid=253084#p253084
You can't do cross-domain AJAX requests like that due to the same-origin policy. Instead, use Facebook's JavaScript SDK, which is based on a script tag.
Does anyone know what is the difference between $("#id").load and $.ajax?
Let me clarify things for you a little bit :
$.ajax() is the basic and low-level ajax function jQuery provides which means you can do what ever you want to like you can work with XmlHttpRequest object. But once upon a time jQuery Developers thought that actually besides $.ajax(), they could provide more specific methods to developers so they wouldn't need to pass more parameters to make $.ajax() method work the way they want. For example they said instead of passing json as a parameter to $.ajax() to indicate return data type, they provided $.getJSON() so we would all know that the return type we expected was json, or instead of indicating send method as post or get, you could use $.post() or $.get() respectively.
So load() is the same thing, it can help you inject html data into your html. with load() method you know that an html portion is being expected.
Isn't that cool ?
I think I've been fallen in love.
For more information, you can visit jquery.com, they are even providing their new library and api tutorial page.
Edit :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
is the same as below :
$.post("some.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Now as you can see it is the simplified version of $.ajax(), to make post call, you need to pass some information of send method type which is post as shown at the first example but instead of doing this you can use $.post() because you know what you are doing is post so this version is more simplified and easy to work on.
But don't forget something. Except for load(), all other ajax methods return XHR (XmlHttpRequest instance) so you can treat them as if you were working with XmlHttpRequest, actually you are working with it tho :) and but load() returns jQuery which means :
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
in the example above, you can easly inject the return html into #objectID element. Isn't it cool ? If it wasn't returning jQuery, you should have been working with callback function where you probably get the result out of like data object and inject it manually into the html element you want. So it would be hassle but with $.load() method, it is really simplified in jQuery.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
You can even post parameters, so according to those parameters you can do some work at server-side and send html portion back to the client and your cute jQuery code takes it and inject it into #feeds html element in the example right above.
load() initiates an Ajax request to retrieve HTML that, when returned, is set to the given selector.
All the jQuery Ajax functions are simply wrappers for $.ajax() so:
$("#id").load(...);
is probably equivalent to:
$.ajax({
url: "...",
dataType: "html",
success: function(data) {
$("#id").html(data);
}
});
A more concise summary and the most important difference is that $.ajax allows you to set content-type and datatype.
These two are important for making JSON requests, or XML requests. ASP.NET is more fussy with a missing content-type field (atleast when you use [WebMethod]) and will simply return the HTML of the page instead of JSON.
$.load() is intended to simply return straight HTML. $.ajax also gives you
caching
error handling
filtering of data
password
plus others.
From the documentation ...
$(selector).load(..)
Load HTML from a remote file and inject it into the DOM.
$.ajax(...)
Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
load is specifically for fetching (via GET unless parameters are provided, then POST is used) an HTML page and directly inserting it into the selected nodes (those selected by the $(selector) portion of $(selector).load(...).
$.ajax(...) is a more general method that allows you to make GET and POST requests, and does nothing specific with the response.
I encourage you to read the documentation.
Here's the source code for the load function: http://github.com/jquery/jquery/blob/master/src/ajax.js#L15
As you can see, it's a $ajax with some options handling. In other words, a convenience method.
The above answer may not be valid anymore in light of the use of deferred and promise objects. I believe that with .ajax you can use .when but you cannot do so with .load. In short, I believe that .ajax is more powerful than .load. For example:
some_promise = $.ajax({....});
.when(some_promise).done(function(){.... });
You get more granular control over the html loading. There is also .fail and .always for failure and "no matter what" cases. You don't get this in load. Hope I am correct on this.