Skip to content

Converted code examples in ajax and effects #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 15, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions page/ajax/ajax-and-forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,24 @@ Serializing form inputs in jQuery is extremely easy. Two methods come supported

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">
```
// Turning form data into a query string
$('#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">
```
// Creating an array of objects containing form data
$('#myForm').serializeArray();

// creates a structure like this:
// [
// { 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.
Expand All @@ -34,7 +36,8 @@ Please note that it is advisable that you also perform server-side validation fo

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">
```
// 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
Expand All @@ -44,11 +47,12 @@ $("#form").submit(function( e ) {
// 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">
```
// Validate a phone number field
$("#form").submit(function( e ) {
var inputtedPhoneNumber = $("#phone").val()
, phoneNumberRegex = ^\d*$/; // match only numbers
Expand All @@ -61,7 +65,7 @@ $("#form").submit(function( e ) {
// run $.ajax here
}
})
</javascript>
```



Expand All @@ -70,19 +74,21 @@ A prefilter is a way to modify the ajax options before each request is sent (hen

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">
```
// 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">
```
// 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>
```
5 changes: 3 additions & 2 deletions page/ajax/ajax-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ this behavior inside every Ajax request, you can bind Ajax events to elements
just like you'd bind other events. For a complete list of Ajax events, visit
[ Ajax Events documentation on docs.jquery.com ]( http://docs.jquery.com/Ajax_Events ).

<javascript caption="Setting up a loading indicator using Ajax Events">
```
// Setting up a loading indicator using Ajax Events
$('#loading_indicator')
.ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
</javascript>
```
4 changes: 2 additions & 2 deletions page/ajax/ajax-excercises.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ need to leverage the href of that link to get the proper content from
blog.html. Once you have the href, here's one way to process it into an ID
that you can use as a selector in `$.fn.load`:

<javascript>
```
var href = 'blog.html#post1';
var tempArray = href.split('#');
var id = '#' + tempArray[1];
</javascript>
```

Remember to make liberal use of `console.log` to make sure you're on the right
path!
Expand Down
26 changes: 15 additions & 11 deletions page/ajax/jquery-ajax-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ documentation of the configuration options, visit
[http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax
documentation on api.jquery.com").

<javascript caption="Using the core `$.ajax` method">
```
// Using the core `$.ajax` method
$.ajax({
// the URL for the request
url : 'post.php',
Expand Down Expand Up @@ -58,9 +59,9 @@ $.ajax({
alert('The request is complete!');
}
});
</javascript>
```

<div class="note" markdown="1">
<div class="note" >
### Note

A note about the dataType setting: if the server sends back data that is in a
Expand Down Expand Up @@ -191,7 +192,7 @@ The URL for the request. Required.
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`.

<div class="note" markdown="1">
<div class="note">
### Note

This option is not valid for `$.getScript`.
Expand All @@ -208,13 +209,14 @@ object.

The type of data you expect back from the server. Optional.

<div class="note" markdown="1">
<div class="note">
### Note

This option is only applicable for methods that don't already specify the data
type in their name. </div>

<javascript caption="Using jQuery's Ajax convenience methods">
```
// Using jQuery's Ajax convenience methods
// get plain text or html
$.get('/users.php', { userId : 1234 }, function(resp) {
console.log(resp);
Expand All @@ -231,7 +233,7 @@ $.getJSON('/details.php', function(resp) {
console.log(k + ' : ' + v);
});
});
</javascript>
```

### `$.fn.load`

Expand All @@ -241,12 +243,14 @@ uses the returned HTML to populate the selected element(s). 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.

<javascript caption="Using `$.fn.load` to populate an element">
```
// Using `$.fn.load` to populate an element
$('#newContent').load('/foo.html');
</javascript>
```

<javascript caption="Using `$.fn.load` to populate an element based on a selector">
```
// Using `$.fn.load` to populate an element based on a selector
$('#newContent').load('/foo.html #myDiv h1:first', function(html) {
alert('Content updated!');
});
</javascript>
```
10 changes: 5 additions & 5 deletions page/ajax/key-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ For adding a new script to the page

For transporting JSON-formatted data, which can include strings, arrays, and objects

<div class="note" markdown="1">
<div class="note">
### Note

As of jQuery 1.4, if the JSON data sent by your server isn't properly
Expand Down Expand Up @@ -74,19 +74,19 @@ Ajax calls are asynchronous by default, the response is not immediately
available. Responses can only be handled using a callback. So, for example,
the following code will not work:

<javascript>
```
var response;
$.get('foo.php', function(r) { response = r; });
console.log(response); // undefined!
</javascript>
```

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

<javascript>
```
$.get('foo.php', function(response) { console.log(response); });
</javascript>
```

### Same-Origin Policy and JSONP

Expand Down
5 changes: 3 additions & 2 deletions page/ajax/working-with-jsonp.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ particularly great source of JSONP-formatted data is the [Yahoo! Query
Language](http://developer.yahoo.com/yql/console/), which we'll use in the
following example to fetch news about cats.

<javscript caption="Using YQL and JSONP">
```
// Using YQL and JSONP
$.ajax({
url : 'http://query.yahooapis.com/v1/public/yql',

Expand All @@ -31,7 +32,7 @@ $.ajax({
console.log(response);
}
});
</javscript>
```

jQuery handles all the complex aspects of JSONP behind-the-scenes — all we have
to do is tell jQuery the name of the JSONP callback parameter specified by YQL
Expand Down
28 changes: 16 additions & 12 deletions page/effects/built-in-effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,43 +33,45 @@ Hide the selected elements with a vertical sliding motion.
Show or hide the selected elements with a vertical sliding motion, depending on
whether the elements are currently visible.

<javascript caption="A basic use of a built-in effect">
```
// A basic use of a built-in effect
$('h1').show();
</javascript>

### Changing the Duration of Built-in Effects

With the exception of `$.fn.show` and `$.fn.hide`, all of the built-in methods
are animated over the course of 400ms by default. Changing the duration of an
effect is simple.

<javascript caption="Setting the duration of an effect">
```
// Setting the duration of an effect">
$('h1').fadeIn(300); // fade in over 300ms
$('h1').fadeOut('slow'); // using a built-in speed definition
</javascript>
```

### jQuery.fx.speeds

jQuery has an object at `jQuery.fx.speeds` that contains the default speed, as
well as settings for "`slow`" and "`fast`".

<javascript>
```
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
}
</javascript>
```

It is possible to override or add to this object. For example, you may want to
change the default duration of effects, or you may want to create your own
effects speed.

<javascript caption="Augmenting `jQuery.fx.speeds` with custom speed definitions">
```
// Augmenting `jQuery.fx.speeds` with custom speed definitions">
jQuery.fx.speeds.blazing = 100;
jQuery.fx.speeds.turtle = 2000;
</javascript>
```

### Doing Something when an Effect is Done

Expand All @@ -82,15 +84,17 @@ conclusion of the animation. Inside of the callback function, the keyword this
refers to the element that the effect was called on; as we did inside of event
handler functions, we can turn it into a jQuery object via $(this).

<javascript caption="Running code when an animation is complete">
```
// Running code when an animation is complete">
$('div.old').fadeOut(300, function() { $(this).remove(); });
</javascript>
```

Note that if your selection doesn't return any elements, your callback will
never run! You can solve this problem by testing whether your selection
returned any elements; if not, you can just run the callback immediately.

<javascript caption="Run a callback even if there were no elements to animate">
```
// Run a callback even if there were no elements to animate
var $thing = $('#nonexistent');

var cb = function() {
Expand All @@ -102,4 +106,4 @@ returned any elements; if not, you can just run the callback immediately.
} else {
cb();
}
</javascript>
```
12 changes: 7 additions & 5 deletions page/effects/custom-effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ jQuery makes it possible to animate arbitrary CSS properties via the
`$.fn.animate` method. The `$.fn.animate` method lets you animate to a set
value, or to a value relative to the current value.

<javascript caption="Custom effects with `$.fn.animate`">
```
// Custom effects with `$.fn.animate`">
$('div.funtimes').animate(
{
left : "+=50",
Expand All @@ -15,9 +16,9 @@ value, or to a value relative to the current value.
300, // duration
function() { console.log('done!'); // calback
});
</javascript>
```

<div class="note" markdown="1">
<div class="note">
Color-related properties cannot be animated with `$.fn.animate` using jQuery
out of the box. Color animations can easily be accomplished by including the
[color plugin](http://github.com/jquery/jquery-color). We'll discuss using
Expand All @@ -34,15 +35,16 @@ natural transitions in your animations, various easing plugins are available.
As of jQuery 1.4, it is possible to do per-property easing when using the
`$.fn.animate` method.

<javascript caption="Per-property easing">
```
// Per-property easing">
$('div.funtimes').animate(
{
left : [ "+=50", "swing" ],
opacity : [ 0.25, "linear" ]
},
300
);
</javascript>
```

For more details on easing options, see
[Animation documentation on api.jquery.com](http://api.jquery.com/animate/).
4 changes: 2 additions & 2 deletions page/effects/managing-effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ Stop currently running animations on the selected elements.

Wait the specified number of milliseconds before running the next animation.

<javascript>
```
$('h1').show(300).delay(1000).hide(300);
</javascript>
```

### `jQuery.fx.off`

Expand Down
Loading