Skip to content

Commit

Permalink
Merge pull request jquery#56 from connormontgomery/master
Browse files Browse the repository at this point in the history
Ajax-and-forms content; code formatting issue fixes; etc
  • Loading branch information
ajpiano committed Mar 13, 2012
2 parents 3579c92 + f90a3a8 commit 0313baa
Show file tree
Hide file tree
Showing 12 changed files with 129 additions and 60 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -23,7 +23,7 @@ This site consists of content maintained in [Markdown](http://daringfireball.net

The entire site is managed via [this Git repository](https://github.com/jquery/learn.jquery.com). If you'd like to contribute new articles, make edits to existing content, or work on the site itself, the first thing you'll need is a [fork](http://help.github.com/fork-a-repo/). When you have changes you'd like to have reviewed and integrated into the site, submit a [pull request](http://help.github.com/send-pull-requests/).

If you aren't already familiar with Git, you'll still need a fork and a GitHub account, but you can can edit files directly via [GitHub's in-browser editor](https://github.com/blog/905-edit-like-an-ace), but you won't be able to create new content. We encourage you to [learn how to use Git andGitHub](http://help.github.com/), it'll probably pretty useful no matter what.
If you aren't already familiar with Git, you'll still need a fork and a GitHub account, but you can can edit files directly via [GitHub's in-browser editor](https://github.com/blog/905-edit-like-an-ace), but you won't be able to create new content. We encourage you to [learn how to use Git and GitHub](http://help.github.com/), it'll probably pretty useful no matter what.


## How Do I Get This Running Locally?
Expand Down
2 changes: 1 addition & 1 deletion Rules
Expand Up @@ -29,7 +29,7 @@ class Nanoc3::Filter
languages = LANGUAGES.keys.join("|")

until @string.empty?
match = scan_until /(\+(\S.*?\S?)\+|<(#{languages})(?: filename=["']([^"']*)["'])?(?: caption=["']([^"']*)["'])?>|\z)/m
match = scan_until /(\+(\S.*?\S?)\+|<(#{languages})(?: filename=["']([^"']*)["'])?(?: caption=["]([^"]*)["])?>|\z)/m

@pending << match.pre_match

Expand Down
88 changes: 76 additions & 12 deletions content/ajax/ajax-and-forms.md
Expand Up @@ -3,25 +3,89 @@ chapter : ajax
section : 4
title : Ajax and Forms
attribution: jQuery Fundamentals

---
jQuery’s ajax capabilities can be especially useful when dealing with forms.
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. That said, there are a two jQuery methods you
should know that relate to form processing in jQuery: `$.fn.serialize` and
`$.fn.serializeArray`.

jQuery’s ajax capabilities can be especially useful when dealing with forms. There are several advantages, which can range from serialization, to simple client-side validation (e.g. "Sorry, that username is taken"), to [prefilters](http://api.jquery.com/extending-ajax/#Prefilters) (explained below), and even more!

### Serialization
Serializing form inputs in jQuery is extremely easy. Two methods come supported natively - `$.fn.serialize` and `$.fn.serializeArray`. While the names are fairly self-explanatory, there are many advantages to using them.

The `serialize` method serializes a form's data into a query string. For the element's value to be serialized, it **must** have a `name` attribute. Please noted that values from inputs with a type of `checkbox` or `radio` are included only if they are checked.


<javascript caption="Turning form data into a query string">
$('#myForm').serialize();
$('#myForm').serialize(); // creates a query string like this: field_1=something&field2=somethingElse
</javascript>

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.

<javascript caption="Creating an array of objects containing form data">
$('#myForm').serializeArray();

// creates a structure like this:
[
{ name : 'field1', value : 123 },
{ name : 'field2', value : 'hello world' }
]
// [
// { name : 'field_1', value : 'something' },
// { name : 'field_2', value : 'somethingElse' }
// ]
</javascript>

### Client-side validation
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.

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.

With that being said, let's jump on in to some examples! First, we'll see how easy it is to check if a required field doesn't have anything in it. If it doesn't, then we'll `return false`, and prevent the form from processing.

<javascript caption="Using validation to check for the presence of an input">
$("#form").submit(function( e ) {
if ( $(".required").val().length === 0 ) { // if .required's value's length is zero
// usually show some kind of error message here
return false; // this prevents the form from submitting
}
else {
// run $.ajax here
}
});
</javascript>

Let's see how easy it is to check for invalid characters in a username:

<javascript caption="Validate a phone number field">
$("#form").submit(function( e ) {
var inputtedPhoneNumber = $("#phone").val()
, phoneNumberRegex = ^\d*$/; // match only numbers

if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) { // if the phone number doesn't match the regex
// usually show some kind of error message ere
return false; // prevent the form from submitting
}
else {
// run $.ajax here
}
})
</javascript>



### Prefiltering
A prefilter is a way to modify the ajax options before each request is sent (hence, the name `prefilter`).

For example, say we would like to modify all crossDomain requests through a proxy. To do so with a prefilter is quite simple:

<javascript caption="Using a proxy with a prefilter">
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.crossDomain ) {
options.url = "http://mydomain.net/proxy/" + encodeURIComponent(options.url );
options.crossDomain = false;
}
});
</javascript>

You can pass in an optional argument before the callback function that specifies which `dataTypes` you'd like the prefilter to be applied to. For example, if we want our prefilter to only apply to `JSON` and `script` requests, we'd do:

<javascript caption="using the optional dataTypes argument">
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
// do all of the prefiltering here, but only for requests that indicate a dataType of "JSON" or "script"
})
</javascript>
4 changes: 2 additions & 2 deletions content/getting-started/downloading-jquery.md
Expand Up @@ -88,7 +88,7 @@ The minified versions, while having a larger file size than the packed versions
## jQuery Git - An Instant WIP Build For Testing

This work-in-progress build (known as jQuery Git) is generated once a minute
from the [ jQuery Git repository ]( http://github.com/jquery/jquery ). It is
from the [jQuery Git repository]( http://github.com/jquery/jquery ). It is
provided as a convenience for anyone that wants to help test changes in the
next version of jQuery.

Expand Down Expand Up @@ -135,7 +135,7 @@ jQuery currently requires the following components to be installed:
** ant: Available on any platform with JDK and ANT installed
* java: A copy of Java, version 1.6.0 or later (required to build the minified version of jQuery).

** Build Process **
**Build Process**

You will now need to use the build system that you chose previously - either <code>make</code> or <code>ant</code>.

Expand Down
8 changes: 4 additions & 4 deletions content/javascript-101/arrays.md
Expand Up @@ -24,16 +24,16 @@ console.log(myArray.length); // logs 2

<javascript caption="Changing the value of an array item">
var myArray = [ 'hello', 'world' ];
myArray[1] = 'changed';
myArray[1] = 'changed'; // myArray is now now ['hello', 'changed']
</javascript>

<javascript caption="Adding elements to an array">
var myArray = [ 'hello', 'world' ];
myArray.push('new');
myArray.push('new'); // myArray is now ['hello', 'world', 'new']
</javascript>

<javascript caption="Working with arrays">
var myArray = [ 'h', 'e', 'l', 'l', 'o' ];
var myString = myArray.join(''); // 'hello'
var mySplit = myString.split(''); // [ 'h', 'e', 'l', 'l', 'o' ]
var myString = myArray.join(''); // myString = 'hello'
var mySplit = myString.split(''); // mySPlit = [ 'h', 'e', 'l', 'l', 'o' ]
</javascript>
55 changes: 27 additions & 28 deletions content/javascript-101/functions.md
Expand Up @@ -25,32 +25,32 @@ used in others' JavaScript code.
## Using Functions

<javascript caption="A simple function">
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
console.log(text);
};
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
console.log(text);
};

greet('Rebecca', 'Hello');
greet('Rebecca', 'Hello');
</javascript>


<javascript caption="A function that returns a value">
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return text;
};
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return text;
};

console.log(greet('Rebecca','hello'));
console.log(greet('Rebecca','hello'));
</javascript>

<javascript caption="A function that returns another function">
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return function() { console.log(text); };
};
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return function() { console.log(text); };
};

var greeting = greet('Rebecca', 'Hello');
greeting();
var greeting = greet('Rebecca', 'Hello');
greeting();
</javascript>

## Immediately-Invoked Function Expression
Expand All @@ -62,11 +62,11 @@ polluting the global namespace with your code — no variables declared inside o
the function are visible outside of it.

<javascript caption="An immediately-invoked function expression">
(function(){
var foo = 'Hello world';
})();
(function(){
var foo = 'Hello world';
})();

console.log(foo); // undefined!
console.log(foo); // undefined!
</javascript>

## Functions as Arguments
Expand All @@ -76,16 +76,15 @@ to variables or passed to other functions as arguments. Passing functions as
arguments is an extremely common idiom in jQuery.

<javascript caption="Passing an anonymous function as an argument">
var myFn = function(fn) {
var result = fn();
console.log(result);
};
var myFn = function(fn) {
var result = fn();
console.log(result);
};

myFn(function() { return 'hello world'; }); // logs 'hello world'
myFn(function() { return 'hello world'; }); // logs 'hello world'
</javascript>

<div class="example" markdown="1">
Passing a named function as an argument
<javascript caption="Passing a named function as an argument">

var myFn = function(fn) {
var result = fn();
Expand All @@ -97,4 +96,4 @@ Passing a named function as an argument
};

myFn(myOtherFn); // logs 'hello world'
</div>
</javascript>
1 change: 1 addition & 0 deletions content/javascript-101/loops.md
Expand Up @@ -128,6 +128,7 @@ the loop's body with the break statement.
You may also want to continue the loop without executing more of the loop's
body. This is done using the continue statement.


<javascript caption="Skipping to the next iteration of a loop">
for (var i = 0; i < 10; i++) {
if (something) {
Expand Down
11 changes: 7 additions & 4 deletions content/javascript-101/objects.md
Expand Up @@ -12,23 +12,26 @@ called a method of the object. Otherwise, they are called properties.
As it turns out, nearly everything in JavaScript is an object -- arrays,
functions, numbers, even strings -- and they all have properties and methods.

<javascript caption="Creating an 'object literal'">

<javascript caption="Creating an object literal">
var myObject = {
sayHello : function() {
console.log('hello');
},

myName : 'Rebecca'
};

myObject.sayHello(); // logs 'hello'

console.log(myObject.myName); // logs 'Rebecca'
</javascript>


When creating object literals, you should note that the key portion of each
key-value pair can be written as any valid JavaScript identifier, a string
(wrapped in quotes) or a number:
<javascript>

<javascript caption="test">
var myObject = {
validIdentifier : 123,
'some string' : 456,
Expand Down
2 changes: 1 addition & 1 deletion content/javascript-101/scope.md
Expand Up @@ -53,7 +53,7 @@ sayHello(); // logs 'hello'
console.log(foo); // logs 'world'
</javascript>

<javascript caption="Functions can "see" changes in variable values after the function is defined">
<javascript caption="Functions can see changes in variable values after the function is defined">
var myFunction = function() {
var foo = 'hello';

Expand Down
2 changes: 1 addition & 1 deletion content/javascript-101/testing-type.md
Expand Up @@ -17,7 +17,7 @@ var myFunction = function() {
};

var myObject = {
foo : 'bar'
foo : 'bar'
};

var myArray = [ 'a', 'b', 'c' ];
Expand Down
6 changes: 4 additions & 2 deletions content/jquery-basics/css-styling-dimensions.md
Expand Up @@ -31,6 +31,8 @@ contains multiple properties. This is a common way to pass multiple arguments
to a function, and many jQuery setter methods accept objects to set mulitple
values at once.

**Note:** while we do not recommend using `$.fn.css` as a setter in production-ready code (see below), when passing in an object to set CSS, CSS properties will be camelCased, instead of using a hypen.

### Using CSS Classes for Styling

As a getter, the `$.fn.css` method is valuable; however, it should generally be
Expand All @@ -39,15 +41,15 @@ presentational information in your JavaScript. Instead, write CSS rules for
classes that describe the various visual states, and then simply change the
class on the element you want to affect.

<javscript caption="Working with classes">
<javascript caption="Working with classes">
var $h1 = $('h1');

$h1.addClass('big');
$h1.removeClass('big');
$h1.toggleClass('big');

if ($h1.hasClass('big')) { ... }
</javscript>
</javascript>

Classes can also be useful for storing state information about an element, such as indicating that an element is selected.

Expand Down
8 changes: 4 additions & 4 deletions layouts/footer.html
Expand Up @@ -9,12 +9,12 @@
<h3><span>Quick Access</span></h3>
<div class="cdn">
<strong>CDN</strong>
<span>//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js</span>
<span>//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js</span>
</div>
<div class="download">
<strong>Download jQuery 1.5.1:</strong>
<span><a href="#">Minified <em>(29KB)</em></a>
<a href="#">Unminified <em>(212KB)</em></a></span>
<strong>Download jQuery 1.7.1:</strong>
<span><a href="//code.jquery.com/jquery-1.7.1.min.js">Minified <em>(29KB)</em></a>
<a href="//code.jquery.com/jquery-1.7.1.js">Unminified <em>(212KB)</em></a></span>
</div>
<ul class="footer-icon-links">
<li class="footer-icon icon-github"><a href="http://github.com/jquery/jquery">Github <small>jQuery <br>Source</small></a></li>
Expand Down

0 comments on commit 0313baa

Please sign in to comment.