The method getmakes a GET request to the server, that is, all requested data is transmitted in the query string.
It accepts the following parameters:
- url: required parameter containing the address of the resource that the request will access
- data: optional parameter containing a simple javascript object or string to be sent to the server along with the request
- success(data, textStatus, jqXHR): optional parameter – a callback function that will be executed when the request is successful. It can take three parameters: data- the data received from the server, textStatus- the status of the request, and jqXHR- a special jQuery object that represents an extended version of the XMLHttpRequest object .
- dataType: optional parameter containing the data type as a string, such as “xml” or “json”
On output, the get method returns an object jqXHRthat will encapsulate the request data. We will discuss this object in more detail later.
So let’s rewrite the example from the previous paragraph using the method get:
$(function(){ $('button').click(function(){ $.get('ajax.php', function(data) { $('#news').html(data); alert('Data loaded'); }); }); });
The first two parameters are used here: the address of the resource and the callback function. In this function, as the data parameter, we receive the data received from the server and load it as markup into the selection element ( $(‘#news’).html(data);). Essentially the same thing we could do with the load.
Sending data
Using the data parameter, we can send additional data. For example, you can send a request to get an element from the database by id:
$.get('ajax.php', { id: "1"});
And since in a GET request all data is transmitted in the query string, this code will be similar to the following:
$.get('ajax.php?id=1');
Accordingly, on the server side, we can get this parameter and perform any actions with it, for example, get an element from the database by a given id:
<?php $id=$_GET['id']; ?>
Using a data type
Often there is such a situation when the server sends data in a certain format, for example, json or xml. So, a php file on the server side might look like this:
<?php echo json_encode(array("event"=>"Start of USA Championship","date"=>"13.07.2013")); ?>
In this case, it returns a JSON object. Then on the client side we can explicitly set the data type, and process the received data in the function:
$.get('ajax.php', function(data) { $('#news').empty().append("<h3>"+data.event+"</h3><h5>"+data.date+"</h5>"); }, 'json');