Skip to content

Commit c7b71e6

Browse files
committed
update examples to core styls in AJAX section
1 parent a9d30b5 commit c7b71e6

6 files changed

+151
-77
lines changed

page/ajax/ajax-and-forms.md

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,35 @@ The `serialize` method serializes a form's data into a query string. For the ele
1212

1313
```
1414
// Turning form data into a query string
15-
$('#myForm').serialize(); // creates a query string like this: field_1=something&field2=somethingElse
15+
$("#myForm").serialize(); // creates a query string like this: field_1=something&field2=somethingElse
1616
1717
```
1818

1919
While plain old serialization is great, sometimes your application would work better if you sent over an array of objects, instead of just the query string. For that, jQuery has the `serializeArray` method. It's very similar to the `serialize` method listed above, except it produces an array of objects, instead of a string.
2020

2121
```
2222
// Creating an array of objects containing form data
23-
$('#myForm').serializeArray();
23+
$("#myForm").serializeArray();
2424
2525
// creates a structure like this:
2626
// [
27-
// { name : 'field_1', value : 'something' },
28-
// { name : 'field_2', value : 'somethingElse' }
27+
// {
28+
//
29+
// name : "field_1",
30+
// value : "something"
31+
//
32+
// },
33+
// {
34+
//
35+
// name : "field_2",
36+
// value : "somethingElse"
37+
//
38+
// }
2939
// ]
3040
```
3141

3242
### Client-side validation
33-
Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc..., or checking an "I agree..." box.
43+
Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc..., or checking an "I agree..." box.
3444

3545
Please note that it is advisable that you also perform server-side validation for your inputs. However, it typically makes for a better user experience to be able to validate some things without submitting the form.
3646

@@ -39,13 +49,18 @@ With that being said, let's jump on in to some examples! First, we'll see how ea
3949
```
4050
// Using validation to check for the presence of an input
4151
$("#form").submit(function( e ) {
52+
4253
if ( $(".required").val().length === 0 ) { // if .required's value's length is zero
54+
4355
// usually show some kind of error message here
4456
return false; // this prevents the form from submitting
45-
}
46-
else {
57+
58+
} else {
59+
4760
// run $.ajax here
61+
4862
}
63+
4964
});
5065
```
5166

@@ -54,20 +69,23 @@ Let's see how easy it is to check for invalid characters in a username:
5469
```
5570
// Validate a phone number field
5671
$("#form").submit(function( e ) {
57-
var inputtedPhoneNumber = $("#phone").val()
58-
, phoneNumberRegex = ^\d*$/; // match only numbers
59-
72+
73+
var inputtedPhoneNumber = $("#phone").val();
74+
var phoneNumberRegex = ^\d*$/; // match only numbers
75+
6076
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) { // if the phone number doesn't match the regex
77+
6178
// usually show some kind of error message ere
6279
return false; // prevent the form from submitting
63-
}
64-
else {
80+
81+
} else {
82+
6583
// run $.ajax here
66-
}
67-
})
68-
```
6984
85+
}
7086
87+
});
88+
```
7189

7290
### Prefiltering
7391
A prefilter is a way to modify the ajax options before each request is sent (hence, the name `prefilter`).
@@ -77,10 +95,15 @@ For example, say we would like to modify all crossDomain requests through a prox
7795
```
7896
// Using a proxy with a prefilter
7997
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
98+
8099
if ( options.crossDomain ) {
100+
81101
options.url = "http://mydomain.net/proxy/" + encodeURIComponent(options.url );
102+
82103
options.crossDomain = false;
104+
83105
}
106+
84107
});
85108
```
86109

@@ -89,6 +112,8 @@ You can pass in an optional argument before the callback function that specifies
89112
```
90113
// Using the optional dataTypes argument">
91114
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
115+
92116
// do all of the prefiltering here, but only for requests that indicate a dataType of "JSON" or "script"
93-
})
117+
118+
});
94119
```

page/ajax/ajax-events.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,14 @@ just like you'd bind other events. For a complete list of Ajax events, visit
1010

1111
```
1212
// Setting up a loading indicator using Ajax Events
13-
$('#loading_indicator')
14-
.ajaxStart(function() { $(this).show(); })
15-
.ajaxStop(function() { $(this).hide(); });
13+
$("#loading_indicator").ajaxStart(function() {
14+
15+
$(this).show();
16+
17+
}).ajaxStop(function() {
18+
19+
$(this).hide();
20+
21+
});
22+
1623
```

page/ajax/ajax-excercises.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ blog.html. Once you have the href, here's one way to process it into an ID
2121
that you can use as a selector in `$.fn.load`:
2222

2323
```
24-
var href = 'blog.html#post1';
25-
var tempArray = href.split('#');
26-
var id = '#' + tempArray[1];
24+
var href = "blog.html#post1";
25+
var tempArray = href.split("#");
26+
var id = "#" + tempArray[1];
2727
```
2828

2929
Remember to make liberal use of `console.log` to make sure you're on the right

page/ajax/jquery-ajax-methods.md

Lines changed: 70 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -24,40 +24,52 @@ documentation of the configuration options, visit
2424
documentation on api.jquery.com").
2525

2626
```
27-
// Using the core `$.ajax` method
27+
// Using the core $.ajax method
2828
$.ajax({
29-
// the URL for the request
30-
url : 'post.php',
31-
32-
// the data to send
33-
// (will be converted to a query string)
34-
data : { id : 123 },
35-
36-
// whether this is a POST or GET request
37-
type : 'GET',
38-
39-
// the type of data we expect back
40-
dataType : 'json',
41-
42-
// code to run if the request succeeds;
43-
// the response is passed to the function
44-
success : function(json) {
45-
$('<h1/>').text(json.title).appendTo('body');
46-
$('<div class="content"/>')
47-
.html(json.html).appendTo('body');
48-
},
49-
50-
// code to run if the request fails;
51-
// the raw request and status codes are
52-
// passed to the function
53-
error : function(xhr, status) {
54-
alert('Sorry, there was a problem!');
55-
},
56-
57-
// code to run regardless of success or failure
58-
complete : function(xhr, status) {
59-
alert('The request is complete!');
60-
}
29+
30+
// the URL for the request
31+
url : "post.php",
32+
33+
// the data to send
34+
// (will be converted to a query string)
35+
data : {
36+
37+
id : 123
38+
39+
},
40+
41+
// whether this is a POST or GET request
42+
type : "GET",
43+
44+
// the type of data we expect back
45+
dataType : "json",
46+
47+
// code to run if the request succeeds;
48+
// the response is passed to the function
49+
success : function( json ) {
50+
51+
$("<h1/>").text( json.title ).appendTo("body");
52+
53+
$("<div class=\"content\"/>").html( json.html ).appendTo("body");
54+
55+
},
56+
57+
// code to run if the request fails;
58+
// the raw request and status codes are
59+
// passed to the function
60+
error : function( xhr, status ) {
61+
62+
alert("Sorry, there was a problem!");
63+
64+
},
65+
66+
// code to run regardless of success or failure
67+
complete : function( xhr, status ) {
68+
69+
alert("The request is complete!");
70+
71+
}
72+
6173
});
6274
```
6375

@@ -218,20 +230,32 @@ type in their name. </div>
218230
```
219231
// Using jQuery's Ajax convenience methods
220232
// get plain text or html
221-
$.get('/users.php', { userId : 1234 }, function(resp) {
222-
console.log(resp);
233+
$.get( "/users.php", {
234+
235+
userId : 1234
236+
237+
}, function( resp ) {
238+
239+
console.log( resp );
240+
223241
});
224242
225243
// add a script to the page, then run a function defined in it
226-
$.getScript('/static/js/myScript.js', function() {
244+
$.getScript( "/static/js/myScript.js", function() {
245+
227246
functionFromMyScript();
247+
228248
});
229249
230250
// get JSON-formatted data from the server
231-
$.getJSON('/details.php', function(resp) {
232-
$.each(resp, function(k, v) {
233-
console.log(k + ' : ' + v);
251+
$.getJSON( "/details.php", function( resp ) {
252+
253+
$.each( resp, function( k, v ) {
254+
255+
console.log( k + " : " + v );
256+
234257
});
258+
235259
});
236260
```
237261

@@ -244,13 +268,15 @@ providing a URL to the method, you can optionally provide a selector; jQuery
244268
will fetch only the matching content from the returned HTML.
245269

246270
```
247-
// Using `$.fn.load` to populate an element
248-
$('#newContent').load('/foo.html');
271+
// Using $.fn.load to populate an element
272+
$("#newContent").load("/foo.html");
249273
```
250274

251275
```
252-
// Using `$.fn.load` to populate an element based on a selector
253-
$('#newContent').load('/foo.html #myDiv h1:first', function(html) {
254-
alert('Content updated!');
276+
// Using $.fn.load to populate an element based on a selector
277+
$("#newContent").load( "/foo.html #myDiv h1:first:", function( html ) {
278+
279+
alert("Content updated!"");
280+
255281
});
256282
```

page/ajax/key-concepts.md

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,27 @@ available. Responses can only be handled using a callback. So, for example,
7575
the following code will not work:
7676

7777
```
78-
var response;
79-
$.get('foo.php', function(r) { response = r; });
80-
console.log(response); // undefined!
78+
var response;
79+
80+
$.get( "foo.php", function( r ) {
81+
82+
response = r;
83+
84+
});
85+
86+
console.log( response ); // undefined!
8187
```
8288

8389
Instead, we need to pass a callback function to our request; this callback will
8490
run when the request succeeds, at which point we can access the data that it
8591
returned, if any.
8692

8793
```
88-
$.get('foo.php', function(response) { console.log(response); });
94+
$.get( "foo.php", function( response ) {
95+
96+
console.log( response );
97+
98+
});
8999
```
90100

91101
### Same-Origin Policy and JSONP

page/ajax/working-with-jsonp.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,31 @@ following example to fetch news about cats.
1212
```
1313
// Using YQL and JSONP
1414
$.ajax({
15-
url : 'http://query.yahooapis.com/v1/public/yql',
15+
16+
url : "http://query.yahooapis.com/v1/public/yql",
1617
1718
// the name of the callback parameter,
1819
// as specified by the YQL service
19-
jsonp : 'callback',
20+
jsonp : "callback",
2021
2122
// tell jQuery we're expecting JSONP
22-
dataType : 'jsonp',
23+
dataType : "jsonp",
2324
2425
// tell YQL what we want and that we want JSON
2526
data : {
26-
q : 'select title,abstract,url from search.news where query="cat"',
27-
format : 'json'
27+
28+
q : "select title,abstract,url from search.news where query=\"cat\"",
29+
format : "json"
30+
2831
},
2932
3033
// work with the response
31-
success : function(response) {
32-
console.log(response);
34+
success : function( response ) {
35+
36+
console.log( response );
37+
3338
}
39+
3440
});
3541
```
3642

0 commit comments

Comments
 (0)