Recent Posts
Feed
Search
Categories
Archives
Blog Search
Contact
Tags
403 404 500 ajax album ARGS arguetron art artwork B.E.O.T.C.H basic bookmark business code diagram easy eclipse enterprise error family fast forbidden how to html idea ideas itunes java javascript keyboard lazy links money music programming prototype research shortcut social network startup T.R.A.M.P tutorial xmlTags: , 403, 404, 500, diagram, error, forbidden
In AJAX Fast and Easy - part one, we defined AJAX and decided it wasn’t really that complicated. In AJAX Fast and Easy - part two, we created an index.html file, a backendHTML.html file and we downloaded the Prototype Javascript framework. We put them all together and made some ajax magic happen. However, in part 2 we left out all the junk about XML, and all we really did was display the ajax results as an alert. Not too useful, but it proved the point and it was pretty fun.
Today we are going to kick some ajax ass. We are going to get it to do all kinds of useful junk for us. First we will make an ajax call to our backend page and stuff that response into our index page. Then we will make an actual XML file, call it with ajax, parse the XML and render the data on our index page. By the time we are done, you will have some pretty functional code that you will be able to use on your own projects.
Ready to get going? Ok, make sure you got all your files from part one and two in C:\ajaxHowTo\. If you lost them, or you didn’t do part one or two, or you’re just lazy, you can download a zip file with all of the source code already written for you.
Just like we did in part two, we are going to take this step by step.
function getHTML() {
new Ajax.Request('backendHTML.html', {
method:'get',
onSuccess: getHTMLSuccess,
onFailure: getHTMLFailure
});
}
You’ll notice that the only difference between this function and our first function, getSampleHTML, are the onSuccess and onFailure pieces. What we are doing here is telling the ajax call to call two new functions, that we haven’t written yet, on a success or failure.
function getHTMLSuccess(originalRequest) {
var response = originalRequest.responseText;
$('htmlResult').innerHTML = response;
}
function getHTMLFailure() {
alert('woops, what happened?');
}
Lets take a minute to figure out what it is we are trying to do here.
We wrote the new ajax call and named it getHTML, nothing new, we only changed the onSuccess and onFailure calls. Then we created the getHTMLSuccess function. What this function does is, it accepts the ajax response as originalRequest as you can see in getHTMLSuccess(originalRequest). We create a variable named response and set it equal to the response text. The response text will be the html that gets sent back, just like in our alert from part two. The difference here is instead of displaying the response in a javascript alert, we are assigning it to a variable and stuffing the html response into our ‘htmlResult’ div further below in the body of our html. Are you asking “where the hell did we do that?” No problem, I kind of snuck it in there. The prototype framework has some cool special shortcuts for doing everyday javascript junk. In this case, we have the $ sign. The $ sign with prototype is used as a shortcut for “document.getElementById(’htmlResult’)”. If it still doesn’t make sense, just take my word for it. The $(’htmlResult’).innerHTML = response; line will insert the ajax response into our htmlResult div and the content on the page will be magically updated.
The second function we wrote is getHTMLFailure. As you can tell, its only job is to show an alert if a failure occurs. Normally, under these circumstances, the only time you can get a failure is if the backendHTML.html file can’t be found.
That’s ajax man! That’s really all there is to it. Just like in part two, we use prototype to make an ajax call to our backend page, but instead of showing the response in an alert, we display it on the page. Much more useful if you ask me.
Now it’s time for us to put it in high gear and see what this ajax stuff is really all about and how it got its name.
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>The Shining</title>
<author>Stephen King</author>
<ISBN>0743437497</ISBN>
</book>
<book>
<title>Fahrenheit 451</title>
<author>Ray Bradbury</author>
<ISBN>9506440298</ISBN>
</book>
</books>
function getXML() {
new Ajax.Request('backendXML.xml', {
method:'get',
onSuccess: getXMLSuccess,
onFailure: getHTMLFailure
});
}
function getXMLSuccess(originalRequest) {
var response = originalRequest.responseXML;
var numberOfBooks = response.getElementsByTagName('book').length;
var titles = response.getElementsByTagName('title');
var authors = response.getElementsByTagName('author');
var isbns = response.getElementsByTagName('ISBN');
var resultText = "";
resultText = "Total number of books = " + numberOfBooks;
for( i=0; i<numberOfBooks; i++ ) {
currentTitle = titles[i].firstChild.nodeValue;
currentAuthor = authors[i].firstChild.nodeValue;
currentIsbn = isbns[i].firstChild.nodeValue;
resultText = resultText + "<p>";
resultText = resultText + "<br/> Book " + (i+1);
resultText = resultText + "<br/> Title = " + currentTitle;
resultText = resultText + "<br/> Author = " + currentAuthor;
resultText = resultText + "<br/> ISBN = " + currentIsbn;
resultText = resultText + "</p>";
}
$('xmlResult').innerHTML = resultText;
}
Just like the earlier function we wrote, getHTMLSuccess, this new function accepts originalRequest as the ajax response. We assign the response to a variable named response, but this time we use originalRequest.responseXML instead of responseText. That part is important and you must use responseXML if we are going to parse the XML file to extract the data we want from it.
The reason we would do this is because, unlike making an ajax call to an HTML file and displaying the entire file,
we want to call an XML file and only extract the specific data that we want from it. Remember in part one, we said that
the XML nodes only define what the data means? Well, the
First we need to find out how many books we have, so take a look at the numberOfBooks variable. This variable counts the book nodes. In this case there are two. The next variable is titles, this variable gets all the nodes named title from the XML. The same goes for authors, and isbns.
We define an empty string called resultText that will be a place holder for some HTML we will build in a minute. We then start adding text to the new resultText string to display the total number of books found on the XML file.
Next we create a loop to repeat the same procedures for each book, in this case we will loop twice. Our loop creates three variables and assigns the node values to them. I’ll give one example of how it works and the rest should be self-explanatory. currentTitle = titles[i].firstChild.nodeValue means that on the first round of the loop we are looking for titles[0].firstChild.nodeValue, which means… Give me the nodeValue, in this case ‘The Shining’ of the first item in the XML file named title (<title>The Shining</title>).
The rest of the script just does the same thing over and over again for as many books as we have in the XML file. We get the values from the XML, we assign them to variables, we attach the values to the resultText variable, we add some normal HTML junk around them to make them look pretty, then we do the prototype magic again.
We use the $ sign to update the div xmlResult with the text we just created in our resultText variable. Again, this is nothing new, its simply document.getElementById(’xmlResult’).innerHTML = “the junk we just looped through”.
That example took a little longer to explain, but that is pretty much everything you need to know about ajax.
Page A makes an AJAX call to page B, and page A displays the content of page B.
If you want to call an HTML page, fine. If you want to call an XML file to extract data from, fine. Either way, you have a page that makes a call to a backend page. Normally you will have some sort of server side technology on the backend page like PHP or java that runs database queries and gets dynamic content, but that has nothing to do with ajax itself.
I am a huge fan of the Prototype Javascript framework, and there are ton of other shortcuts like the $ sign built into it. There are also other ways to make ajax calls with prototype that actually make the job we just worked even easier, but for the sake of the explanation, we didn’t use them. I will try to put together another post that goes over some of the most useful things you can do with prototype in the future.
Here is a cheat sheet for prototype that you will probably find useful.
Well, that’s it. Now you know ajax. It’s no big secret, it’s not complicated, and it’s pretty fun.
What would you like the hear about next?
Tags: ajax, basic, code, easy, fast, how to, html, javascript, prototype, tutorial, xml
Random numbers in Javascript are stupid.
It’s hard to get Javascript to give you the kind of random numbers that you want. A while ago, I struggled with this issue myself and this blog gave me enough information to get my project completed. Thank you Andrew Penry for the great article on Javascript Math.random()
Recently the Web Cash blog wrote an article about random numbers in Javascript. Both articles are similar and I bet they would have fun arguing about why each added their digit in a different order of operation.
After reading both of those articles, you should be able to use random Javascript numbers in any project, however, the overachievers at Web Cash decided to take it one step further and stop the conversation for everyone by creating a helper function that everyone could use in any project where random numbers are necessary. If you need a random number, read Javascript Function: Random Number Generator, I would recommend you use it in your next project.
My dog Howie just farted, so i’ll have to leave the room, but I promise that I’ll finish Ajax Fast and Easy part three tomorrow.
In “AJAX Fast and Easy - part one“, we defined AJAX. We said the Asynchronous part could be compared to opening a link in a new window so that you don’t leave your current page. We said the Javascript part could be as simple as adding a call to the freely available Prototype Javascript framework. We decided that XML was pretty simple to understand because all it does is describe the data you put in it, and we even went as far as saying that XML is not necessary when writing AJAX.
The first thing we will do in part two is prove that last statement. XML is not necessary to write AJAX. So, without further ado, take out your notepads, or your favorite HTML editor and get ready to write some AJAX code. If you are running a web server, great, but if not, don’t worry about it. If you have Firefox installed, you can run all of this code without a web server.
Lets go about this step by step, so we can see how easy it really is.
- Create a new directory for our files, and name it ajaxHowTo (ex. C:\ajaxHowTo\).
- Create a new file in C:\ajaxHowTo\ named index.html.
- Open index.html for editing and enter the code below to create a simple web page.
<html>
<head>
<title>Ajax How To</title>
<script src="prototype-1.6.0.2.js" type="text/javascript"></script>
</head>
<body>
<p>
<a href="javascript: void(0);" onclick="getSampleHTML();">call getSampleHTML()</a>
and display results in alert from sample code
</p>
<p>
<a href="javascript: void(0);" onclick="getHTML();">call getHTML()</a>
and display results in a div below
<a href="javascript: void(0);" onclick="clearNode('htmlResult');">clear</a>
</p>
<p>
<a href="javascript: void(0);" onclick="getXML();">call getXML()</a>
and display results in a div below
<a href="javascript: void(0);" onclick="clearNode('xmlResult');">clear</a>
</p>
<p>Display the AJAX results below:</p>
<div id="htmlResult">
</div>
<div id="xmlResult">
</div>
</body>
</html>
Feel free to open up your index.html file and view it in a web browser. The links won’t do much right now because we haven’t written the javascript functions yet, but it should look like this. For the very lazy, I have packed all the sample code in a zip file for download.
<html>
<head>
<title>Ajax How To</title>
<script src="prototype-1.6.0.2.js" type="text/javascript"></script>
<script>
</script>
</head>
<body>
function getSampleHTML() {
new Ajax.Request('backendHTML.html', {
method:'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){
alert('Something went wrong...')
}
});
}
<html>
<head>
<title>Ajax How To</title>
</head>
<body>
Hey, you just wrote some AJAX!!
<br/>
Wasn't that EASY!!!!
</body>
</html>
We should now have 3 files inside of our new folder /ajaxHowTo/. We should have index.html, backendHTML.html, and prototype-1.6.0.2.js.
That is all we need. We just wrote our first AJAX code! Wasn’t that easy? Just two HTML files and one javascript function!
Now, go ahead and open index.html. Click on the first link labeled “call getSampleHTML()”. Clicking that link causes a call to our Javascript function named getSampleHTML(). That function calls a function built into Prototype called Ajax.Request(). Ajax.Request() gets passed the name of the file we want to call via AJAX, in this case “backendHTML.html”. In the onSuccess section of our function, we specified that we want an alert to appear with the words “Success!” followed by the content of the file we called through AJAX.
Thats all there is to it!
It’s as simple as 1,2,3!
Page A makes an AJAX call to page B, and page A displays the content of page B.
Thats AJAX!
That concludes “Ajax Fast and Easy - part two”. In part three, we will expand on these files by adding the ability to render the AJAX response on the current page as HTML, and we will make a call to an actual XML file, parse the XML and render the XML response on the page as well. Don’t worry, I promise it will be fast and easy.
UPDATE:
Ajax Fast and Easy - part three is now available
Tags: ajax, basic, code, easy, fast, how to, html, javascript, tutorial, xml