Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Recipe: Performing a GET Request

One of the simpler AJAX requests can be executed by using the shorthand method for GET. You can imagine performing a similar call for POST, PUT, and DELETE. Keep in mind that PUT and DELETE are not supported by all browsers, so it is wise to use GET and POST. Listing 5.2 shows the use of the get() method.

Listing 5.2. Fetching JSON Values by using the get() Shorthand Function

00 <!DOCTYPE html>
02 <html lang="en">
03 <head>
04   <title>The AJAX get() request function</title>
05 </head>
06 <body>
08 <h2>Press the button to perform the request.</h2>
10 <button id="trigger">GET</button>
11 <br>
12 <div id="target"></div>
14 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
16 <script>
17 // please externalize this code to an external .js file
18 $(document).ready(function() {
20   $('#trigger').click(function() {
22     $.get('02a-test-values.json', function(data) {
24       $('#target').append('The returned value is: ' + data.name);
26     }, 'json');
27   });
29 });
30 </script>
31 </body>
32 </html>

Line 22 fetches the following JSON document:

  "name": "Adriaan de Jonge",
  "email" : "adriaandejonge@gmail.com"

When executed, this script returns the name of the author. In this example, the success handler function is a callback directly passed to the get() function. The last parameter passed in the get() is 'json'. This is an optional data-type parameter. In this instance, it informs jQuery that the data requested will be returned in JSON format. Later examples demonstrate an alternative approach for callback functions. If you use a web service or have some server-side logic set up to handle data coming in before handing back a response, you can pass an additional set of data to the server through the get() function. To learn more about sending data to the server by using get(), see the official documentation at http://api.jquery.com/jQuery.get/.

  • + Share This
  • 🔖 Save To Your Account