There is a basic problem with jQuery’s .load() method. Namely, it places the results into a single element. What if we wanted to put multiple items into multiple HTML elements, or not necessarily display the returned results – rather storing the values in variables.
Well jQuery provides several additional methods to load data, but the two most common are $.get() and $.post(). There are a few others, but they are not used as often, and won’t be looked at here.
Both of these methods are very similar. The difference is in how does the request get made, either at a POST or a GET – just as if the information was sent via a form. I’m sure you can see the method names, and figure out which one uses which method.
In both of these methods, we see something different from other jQuery calls. Namely, there is no selector. However, just like with the .load() method, you have a mandatory parameter, the URL you are calling.
There are two optional parameters, one to pass the parameters to the URL. Additionally, the return results, for when a successful page is loaded is another parameter, and is function call. The function can then be run when the results are returned, so that you can instruct the page to do different things based upon the results.
An example would look something like:
// use all the parameters with $.get $.get( 'load.php', { 'start': $('#start').val(), 'end': $('#end').val() }, function (data) { alert('data loaded'); $('#content').html(data); } );
You do not have to have both optional parameters. You can work with just one, or neither if you wanted to. For example:
// Do not pass any parameters to this file $.get( 'load.php', function (data) { alert('data loaded'); $('#content').html(data); } ); // send data to the server, but ignore the data that comes back, if any does $.get( 'load.php', { 'start': $('#start').val(), 'end': $('#end').val() } );
Once again, in these examples, the formatting of the code is meant to make it easier for us to read, the computer simply ignores it.
In this example, you can see how we are using .html() to change out the content of an element. This way we can keep any HTML formatting that is made available in the AJAX loaded data. This is a fairly common practice to use.
Using jQuery’s $.get and $.post to Load AJAX Data was originally found on Access 2 Learn