Skip to content

Commit 1d57b6e

Browse files
committed
Add first four sections of ajax
1 parent 30cb2d1 commit 1d57b6e

File tree

4 files changed

+337
-0
lines changed

4 files changed

+337
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
chapter : ajax
3+
section : 4
4+
title : Ajax and Forms
5+
attribution: jQuery Fundamentals
6+
---
7+
## Ajax and Forms
8+
9+
jQuery’s ajax capabilities can be especially useful when dealing with forms.
10+
The [jQuery Form Plugin](http://jquery.malsup.com/form/) is a well-tested tool for adding Ajax capabilities to forms, and you should generally use it for handling forms with Ajax rather than trying to roll your own solution for anything remotely complex.
11+
That said, there are a two jQuery methods you should know that relate to form processing in jQuery: `$.fn.serialize` and `$.fn.serializeArray`.
12+
13+
<div class="example" markdown="1">
14+
Turning form data into a query string
15+
16+
$('#myForm').serialize();
17+
</div>
18+
19+
<div class="example" markdown="1">
20+
Creating an array of objects containing form data
21+
22+
$('#myForm').serializeArray();
23+
24+
// creates a structure like this:
25+
[
26+
{ name : 'field1', value : 123 },
27+
{ name : 'field2', value : 'hello world' }
28+
]
29+
</div>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
chapter : ajax
3+
section : 1
4+
title : Overview
5+
attribution: jQuery Fundamentals
6+
---
7+
## Overview
8+
9+
The XMLHttpRequest method (XHR) allows browsers to communicate with the server without requiring a page reload.
10+
This method, also known as Ajax (Asynchronous JavaScript and XML), allows for web pages that provide rich, interactive experiences.
11+
12+
Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response.
13+
Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it’s imperative that a callback be used to handle the response.
14+
15+
jQuery provides Ajax support that abstracts away painful browser differences.
16+
It offers both a full-featured $.ajax() method, and simple convenience methods such as `$.get()`, `$.getScript()`, `$.getJSON()`, `$.post()`, and `$().load()`.
17+
18+
Most jQuery applications don’t in fact use XML, despite the name “Ajax”; instead, they transport data as plain HTML or JSON (JavaScript Object Notation).
19+
20+
In general, Ajax does not work across domains.
21+
Exceptions are services that provide JSONP (JSON with Padding) support, which allow limited cross-domain functionality.
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
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+
$('&lt;h1/>').text(json.title).appendTo('body');
44+
$('&lt;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&amp;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&amp;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>
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
---
2+
chapter : ajax
3+
section : 2
4+
title : Key Concepts
5+
attribution: jQuery Fundamentals
6+
---
7+
## Key Concepts
8+
9+
Proper use of Ajax-related jQuery methods requires understanding some key concepts first.
10+
11+
### GET vs. Post
12+
13+
The two most common “methods” for sending a request to a server are GET and POST.
14+
It’s important to understand the proper application of each.
15+
16+
The GET method should be used for non-destructive operations — that is, operations where you are only “getting” data from the server, not changing data on the server.
17+
For example, a query to a search service might be a GET request.
18+
GET requests may be cached by the browser, which can lead to unpredictable behavior if you are not expecting it.
19+
GET requests generally send all of their data in a query string.
20+
21+
The POST method should be used for destructive operations — that is, operations where you are changing data on the server.
22+
For example, a user saving a blog post should be a POST request.
23+
POST requests are generally not cached by the browser; a query string can be part of the URL, but the data tends to be sent separately as post data.
24+
25+
### Data Types
26+
27+
jQuery generally requires some instruction as to the type of data you expect to get back from an Ajax request; in some cases the data type is specified by the method name, and in other cases it is provided as part of a configuration object. There are several options:
28+
29+
#### text
30+
For transporting simple strings
31+
32+
#### html
33+
For transporting blocks of HTML to be placed on the page
34+
35+
#### script
36+
For adding a new script to the page
37+
38+
#### json
39+
For transporting JSON-formatted data, which can include strings, arrays, and objects
40+
41+
<div class="note" markdown="1">
42+
### Note
43+
44+
As of jQuery 1.4, if the JSON data sent by your server isn't properly formatted, the request may fail silently.
45+
See [http://json.org](http://json.org) for details on properly formatting JSON, but as a general rule, use built-in language methods for generating JSON on the server to avoid syntax issues.
46+
47+
#### jsonp
48+
For transporting JSON data from another domain
49+
50+
#### xml
51+
For transporting data in a custom XML schema
52+
53+
I am a strong proponent of using the JSON format in most cases, as it provides the most flexibility. It is especially useful for sending both HTML and data at the same time.
54+
55+
### A is for Asynchronous
56+
57+
The asynchronicity of Ajax catches many new jQuery users off guard.
58+
Because Ajax calls are asynchronous by default, the response is not immediately available.
59+
Responses can only be handled using a callback.
60+
So, for example, the following code will not work:
61+
62+
<div class="example" markdown="1">
63+
var response;
64+
$.get('foo.php', function(r) { response = r; });
65+
console.log(response); // undefined!
66+
</div>
67+
68+
Instead, we need to pass a callback function to our request;
69+
this callback will run when the request succeeds, at which point we can access the data that it returned, if any.
70+
71+
<div class="example" markdown="1">
72+
$.get('foo.php', function(response) { console.log(response); });
73+
</div>
74+
75+
### Same-Origin Policy and JSONP
76+
77+
In general, Ajax requests are limited to the same protocol (http or https), the same port, and the same domain as the page making the request.
78+
This limitation does not apply to scripts that are loaded via jQuery's Ajax methods.
79+
80+
The other exception is requests targeted at a JSONP service on another domain.
81+
In the case of JSONP, the provider of the service has agreed to respond to your request with a script that can be loaded into the page using a `&lt;script>` tag, thus avoiding the same-origin limitation; that script will include the data you requested, wrapped in a callback function you provide.
82+
83+
### Ajax and Firebug
84+
85+
Firebug (or the Webkit Inspector in Chrome or Safari) is an invaluable tool for working with Ajax requests.
86+
You can see Ajax requests as they happen in the Console tab of Firebug (and in the Resources > XHR panel of Webkit Inspector), and you can click on a request to expand it and see details such as the request headers, response headers, response content, and more.
87+
If something isn't going as expected with an Ajax request, this is the first place to look to track down what's wrong.

0 commit comments

Comments
 (0)