|
| 1 | +--- |
| 2 | +chapter : ajax |
| 3 | +section : 3 |
| 4 | +title : jQuery's Ajax-Related Methods |
| 5 | +attribution: jQuery Fundamentals |
| 6 | +--- |
| 7 | +## jQuery's Ajax-Related Methods |
| 8 | + |
| 9 | +While jQuery does offer many Ajax-related convenience methods, the core `$.ajax` method is at the heart of all of them, and understanding it is imperative. |
| 10 | +We'll review it first, and then touch briefly on the convenience methods. |
| 11 | + |
| 12 | +I generally use the `$.ajax` method and do not use convenience methods. |
| 13 | +As you'll see, it offers features that the convenience methods do not, and its syntax is more easily understandable, in my opinion. |
| 14 | + |
| 15 | +### `$.ajax` |
| 16 | + |
| 17 | +jQuery’s core `$.ajax` method is a powerful and straightforward way of creating Ajax requests. |
| 18 | +It takes a configuration object that contains all the instructions jQuery requires to complete the request. |
| 19 | +The `$.ajax` method is particularly valuable because it offers the ability to specify both success and failure callbacks. |
| 20 | +Also, its ability to take a configuration object that can be defined separately makes it easier to write reusable code. |
| 21 | +For complete documentation of the configuration options, visit [http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax documentation on api.jquery.com"). |
| 22 | + |
| 23 | +<div class="example" markdown="1"> |
| 24 | +Using the core `$.ajax` method |
| 25 | + |
| 26 | + $.ajax({ |
| 27 | + // the URL for the request |
| 28 | + url : 'post.php', |
| 29 | + |
| 30 | + // the data to send |
| 31 | + // (will be converted to a query string) |
| 32 | + data : { id : 123 }, |
| 33 | + |
| 34 | + // whether this is a POST or GET request |
| 35 | + type : 'GET', |
| 36 | + |
| 37 | + // the type of data we expect back |
| 38 | + dataType : 'json', |
| 39 | + |
| 40 | + // code to run if the request succeeds; |
| 41 | + // the response is passed to the function |
| 42 | + success : function(json) { |
| 43 | + $('<h1/>').text(json.title).appendTo('body'); |
| 44 | + $('<div class="content"/>') |
| 45 | + .html(json.html).appendTo('body'); |
| 46 | + }, |
| 47 | + |
| 48 | + // code to run if the request fails; |
| 49 | + // the raw request and status codes are |
| 50 | + // passed to the function |
| 51 | + error : function(xhr, status) { |
| 52 | + alert('Sorry, there was a problem!'); |
| 53 | + }, |
| 54 | + |
| 55 | + // code to run regardless of success or failure |
| 56 | + complete : function(xhr, status) { |
| 57 | + alert('The request is complete!'); |
| 58 | + } |
| 59 | + }); |
| 60 | +</div> |
| 61 | + |
| 62 | +<div class="note" markdown="1"> |
| 63 | +### Note |
| 64 | + |
| 65 | +A note about the dataType setting: if the server sends back data that is in a different format than you specify, your code may fail, and the reason will not always be clear, because the HTTP response code will not show an error. |
| 66 | +When working with Ajax requests, make sure your server is sending back the data type you're asking for, and verify that the Content-type header is accurate for the data type. |
| 67 | +For example, for JSON data, the Content-type header should be `application/json`. |
| 68 | +</div> |
| 69 | + |
| 70 | +### `$.ajax` Options |
| 71 | + |
| 72 | +There are many, many options for the `$.ajax` method, which is part of its power. |
| 73 | +For a complete list of options, visit [http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax documentation on api.jquery.com"); here are several that you will use frequently: |
| 74 | + |
| 75 | +#### async |
| 76 | +Set to `false` if the request should be sent synchronously. Defaults to `true`. Note that if you set this option to `false`, your request will block execution of other code until the response is received. |
| 77 | + |
| 78 | +#### cache |
| 79 | +Whether to use a cached response if available. Defaults to true for all dataTypes except "script" and "jsonp". When set to false, the URL will simply have a cachebusting parameter appended to it. |
| 80 | + |
| 81 | +#### complete |
| 82 | +A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request. |
| 83 | + |
| 84 | +#### context |
| 85 | +The scope in which the callback function(s) should run (i.e. what `this` will mean inside the callback function(s)). By default, `this` inside the callback function(s) refers to the object originally passed to `$.ajax`. |
| 86 | + |
| 87 | +#### data |
| 88 | +The data to be sent to the server. This can either be an object or a query string, such as `foo=bar&baz=bim`. |
| 89 | + |
| 90 | +#### dataType |
| 91 | +The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified. |
| 92 | + |
| 93 | +#### error |
| 94 | +A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request. |
| 95 | + |
| 96 | +#### jsonp |
| 97 | +The callback name to send in a query string when making a JSONP request. Defaults to "callback". |
| 98 | + |
| 99 | +#### success |
| 100 | +A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object. |
| 101 | + |
| 102 | +#### timeout |
| 103 | +The time in milliseconds to wait before considering the request a failure. |
| 104 | + |
| 105 | +#### traditional |
| 106 | +Set to true to use the param serialization style in use prior to jQuery 1.4. For details, see [http://api.jquery.com/jQuery.param/](http://api.jquery.com/jQuery.param/ "$.param documentation on api.jquery.com"). |
| 107 | + |
| 108 | +#### type |
| 109 | +The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers. |
| 110 | + |
| 111 | +#### url |
| 112 | +The URL for the request. |
| 113 | + |
| 114 | +The `url` option is the only required property of the `$.ajax` configuration object; all other properties are optional. This can also be passed as the first argument to $.ajax, and the options object as the second argument. |
| 115 | + |
| 116 | +### Convenience Methods |
| 117 | + |
| 118 | +If you don't need the extensive configurability of `$.ajax`, and you don't care about handling errors, the Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. |
| 119 | +These methods are just "wrappers" around the core `$.ajax` method, and simply pre-set some of the options on the `$.ajax` method. |
| 120 | + |
| 121 | +The convenience methods provided by jQuery are: |
| 122 | + |
| 123 | +#### $.get |
| 124 | +Perform a GET request to the provided URL. |
| 125 | + |
| 126 | +#### $.post |
| 127 | +Perform a POST request to the provided URL. |
| 128 | + |
| 129 | +#### $.getScript |
| 130 | +Add a script to the page. |
| 131 | + |
| 132 | +#### $.getJSON |
| 133 | +Perform a GET request, and expect JSON to be returned. |
| 134 | + |
| 135 | +In each case, the methods take the following arguments, in order: |
| 136 | + |
| 137 | +#### url |
| 138 | +The URL for the request. Required. |
| 139 | + |
| 140 | +#### data |
| 141 | +The data to be sent to the server. Optional. This can either be an object or a query string, such as `foo=bar&baz=bim`. |
| 142 | + |
| 143 | +<div class="note" markdown="1"> |
| 144 | +### Note |
| 145 | + |
| 146 | +This option is not valid for `$.getScript`. |
| 147 | +</div> |
| 148 | + |
| 149 | +#### success callback |
| 150 | +A callback function to run if the request succeeds. Optional. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object. |
| 151 | + |
| 152 | +#### data type |
| 153 | +The type of data you expect back from the server. Optional. |
| 154 | + |
| 155 | +<div class="note" markdown="1"> |
| 156 | +### Note |
| 157 | + |
| 158 | +This option is only applicable for methods that don't already specify the data type in their name. |
| 159 | +</div> |
| 160 | + |
| 161 | +<div class="example" markdown="1"> |
| 162 | +Using jQuery's Ajax convenience methods |
| 163 | + |
| 164 | + // get plain text or html |
| 165 | + $.get('/users.php', { userId : 1234 }, function(resp) { |
| 166 | + console.log(resp); |
| 167 | + }); |
| 168 | + |
| 169 | + // add a script to the page, then run a function defined in it |
| 170 | + $.getScript('/static/js/myScript.js', function() { |
| 171 | + functionFromMyScript(); |
| 172 | + }); |
| 173 | + |
| 174 | + // get JSON-formatted data from the server |
| 175 | + $.getJSON('/details.php', function(resp) { |
| 176 | + $.each(resp, function(k, v) { |
| 177 | + console.log(k + ' : ' + v); |
| 178 | + }); |
| 179 | + }); |
| 180 | +</div> |
| 181 | + |
| 182 | +### `$.fn.load` |
| 183 | + |
| 184 | +The `$.fn.load` method is unique among jQuery’s Ajax methods in that it is called on a selection. |
| 185 | +The `$.fn.load` method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s). |
| 186 | +In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML. |
| 187 | + |
| 188 | +<div class="example" markdown="1"> |
| 189 | +Using `$.fn.load` to populate an element |
| 190 | + |
| 191 | + $('#newContent').load('/foo.html'); |
| 192 | +</div> |
| 193 | + |
| 194 | +<div class="example" markdown="1"> |
| 195 | +Using `$.fn.load` to populate an element based on a selector |
| 196 | + |
| 197 | + $('#newContent').load('/foo.html #myDiv h1:first', function(html) { |
| 198 | + alert('Content updated!'); |
| 199 | + }); |
| 200 | +</div> |
0 commit comments