Here is a quite straight forward jQuery code I find on one site:
//It simply loads more news
function ReadMore(page){
$("#news-list").html('Loading More News...');
$("#news-list").append('<img src="/images/loading.gif">');
next=parseInt(page)+1;
html=$.get('/morenews.php','page='+page,function (data){
$("#News").append(data);
$("#news-list").html("<a href='javascript:void(0);' onclick='ReadMore("+next+");'>More News</a>");
});
}
My question is:
What kind of datatype is it using? "Expected data type of the response. One of: null, 'xml', 'script', or 'json'. "
What is html=$.get('/newread.php','page='+page,function (data){} in jQuery? I have never seen $.get and there seems to be one parameter page.
Does the server receive something like this: /morenews.php?page=3
This code cant deal with errors. If the server is too busy, let's say, doing nothing for 20 seconds, how can I add some error messages?
By the way, jQuery seems to be a weird language because it constantly create anonymous functions.
page is an integer (although it gets typecast to a string when sent to the server as part of an HTTP GET request). data is an html string.
See jQuery.get( url , data , success() ). It's shorthand for $.ajax(). The success() function is a callback, which gets exectuted once a response is received from the server.
Yes: /morenews.php?page=3
You could try adding a timeout function to cancel the request if there's been no response within a given time.
The language is Javascript (jQuery is just a library), and anonymous functions are really cool when you get used to them...
get() is used by jQuery to load data from a server using an HTTP get request. There's also a .post() method to use a post request, etc.
More info on .get() can be found here.....
http://api.jquery.com/jQuery.get/
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 am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.
I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.
I'm seeing a weird error in one of my ajax-updated pages.
The request looks like this:
var a = new Ajax(url,{
method: 'get',
onComplete: function( response ){
$('loader').style.display="none";
readData( response );
}
});
a.request();
return;
This works fine on almost any system so far, but on a new server it breaks, with a mootools error "unknown XML entity". The weird part is, if you trace the request with firebug, rather than returning JSON as expected, the response body looks like this:
<script>document.location.href='http://www.mysite.com?myparams=value&etc;</script>
However, if you actually make that request manually by pasting the URL in the script tag (response body) along with the params in a browser, the proper JSON data is returned.
Any ideas why the request would return a script tag instead of the data?
As Dimitar suggested in the comments above, this was an issue in a Joomla site thanks to a URL rewrite tool called sh404SEF. According to the developer, the fix is to set the "301 redirect" parameter to "no" in the advanced configuration options.
So this had nothing to do with my code or the ajax functions, but was rather the SEF rewrite component that was breaking the request.
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.