-
Notifications
You must be signed in to change notification settings - Fork 177
Completed Ajax Without jQuery Recipe #47
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9c9df33
Added Ajax Without jQuery recipe.
OakRaven 1d4c372
Closed highlighting section with missing {% endhighlight %}.
OakRaven c9c11fb
Added Ajax chapter.
OakRaven f783b80
Updated authors and wanted-recipes removing completed recipes.
OakRaven 457b3a4
Added Ajax chapter.
OakRaven c943705
Simplified code examples and reworked recipe text.
OakRaven 07f559d
Merge branch 'ajax-non-jquery'
OakRaven File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
--- | ||
layout: recipe | ||
title: Ajax Request Without jQuery | ||
chapter: Ajax | ||
--- | ||
## Problem | ||
|
||
You want to load data from your server via AJAX without using the jQuery library. | ||
|
||
## Solution | ||
|
||
You will use the native <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" target="_blank">XMLHttpRequest</a> object. | ||
|
||
Let's set up a simple test HTML page with a button. | ||
|
||
{% highlight html %} | ||
<!DOCTYPE HTML> | ||
<html lang="en-US"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title>XMLHttpRequest Tester</title> | ||
</head> | ||
<body> | ||
<h1>XMLHttpRequest Tester</h1> | ||
<button id="loadDataButton">Load Data</button> | ||
|
||
<script type="text/javascript" src="XMLHttpRequest.js"></script> | ||
</body> | ||
</html> | ||
{% endhighlight %} | ||
|
||
When the button is clicked, we want to send an Ajax request to the server to retrieve some data. For this sample, we have a small JSON file. | ||
|
||
{% highlight javascript %} | ||
// data.json | ||
{ | ||
message: "Hello World" | ||
} | ||
{% endhighlight %} | ||
|
||
Next, create the CoffeeScript file to hold the page logic. The code in this file creates a function to be called when the Load Data button is clicked. | ||
|
||
{% highlight coffeescript linenos %} | ||
# XMLHttpRequest.coffee | ||
loadDataFromServer = -> | ||
req = new XMLHttpRequest() | ||
|
||
req.addEventListener 'readystatechange', -> | ||
if req.readyState is 4 # ReadyState Compelte | ||
if req.status is 200 or req.status is 304 # Success result codes | ||
data = eval '(' + req.responseText + ')' | ||
console.log 'data message: ', data.message | ||
else | ||
console.log 'Error loading data...' | ||
|
||
req.open 'GET', 'data.json', false | ||
req.send() | ||
|
||
loadDataButton = document.getElementById 'loadDataButton' | ||
loadDataButton.addEventListener 'click', loadDataFromServer, false | ||
{% endhighlight %} | ||
|
||
## Discussion | ||
|
||
In the above code we essentially grab a handle to the button in our HTML (line 16) and add a *click* event listener (line 17). In our event listener, we define our callback function as loadDataFromServer. | ||
|
||
We define our loadDataFromServer callback beginning on line 2. | ||
|
||
We create a XMLHttpRequest request object (line 3) and add a *readystatechange* event handler. This fires whenever the request's readyState changes. | ||
|
||
In the event handler we check to see if the readyState = 4, indicating the request has completed. Then, we check the request status value. Both 200 or 304 represent a succsessful request. Anything else represents an error condition. | ||
|
||
If the request was indeed successful, we eval the JSON returned from the server and assign it to a data variable. At this point, we can use the returned data in any way we need to. | ||
|
||
The last thing we need to do is actually make our request. | ||
|
||
Line 13 opens a 'GET' request to retreive the data.json file. | ||
|
||
Line 14 sends our request to the server. | ||
|
||
## Older Browser Support | ||
|
||
If your application needs to target older versions of Internet Explorer, you will need to ensure the XMLHttpRequest object exists. You can do this by including this code before creating the XMLHttpRequest instance. | ||
|
||
{% highlight coffeescript %} | ||
if (typeof @XMLHttpRequest == "undefined") | ||
console.log 'XMLHttpRequest is undefined' | ||
@XMLHttpRequest = -> | ||
try | ||
return new ActiveXObject("Msxml2.XMLHTTP.6.0") | ||
catch error | ||
try | ||
return new ActiveXObject("Msxml2.XMLHTTP.3.0") | ||
catch error | ||
try | ||
return new ActiveXObject("Microsoft.XMLHTTP") | ||
catch error | ||
throw new Error("This browser does not support XMLHttpRequest.") | ||
{% endhighlight %} | ||
|
||
This code ensures the XMLHttpRequest object is available in the global namespace. | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://coffeescript-cookbook.github.io/chapters/ajax/ajax_request_without_jquery
U should remove
linenos
, as I understand