27.10.2015 Views

AJAX and PHP

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Client-Side Techniques with Smarter JavaScript<br />

What Just Happened?<br />

The code is pretty simple. In the HTML code, the important details are highlighted in the<br />

following code snippet:<br />

<br />

<br />

<br />

<strong>AJAX</strong> Foundations: More JavaScript <strong>and</strong> DOM<br />

<br />

<br />

<br />

Hello Dude! Here's a cool list of colors for you:<br />

<br />

<br />

<br />

<br />

Everything starts by referencing the JavaScript source file using the element. The<br />

JavaScript file contains a function called process(), which is used as an event-h<strong>and</strong>ler function<br />

for the body's onload event. The onload event fires after the HTML file is fully loaded, so when<br />

the process() function executes, it has access to the whole HTML structure. Your process()<br />

function starts by creating the HTML code you want to add to the div element:<br />

function process()<br />

{<br />

// Create the HTML code<br />

var string;<br />

string = ""<br />

+ "Black"<br />

+ "Orange"<br />

+ "Pink"<br />

+ "";<br />

Next, you obtain a reference to myDivElement, using the getElementById function of the<br />

document object. Remember that document is a default object in JavaScript, referencing the body<br />

of your HTML document.<br />

// obtain a reference to the element on the page<br />

myDiv = document.getElementById("myDivElement");<br />

Note that JavaScript allows you to use either single quotes or double quotes for string<br />

variables. The previous line of code can be successfully written like this:<br />

myDiv = document.getElementById('myDivElement');<br />

In the case of JavaScript, both choices are equally good, as long as you are consistent<br />

about using only one of them. If you use both notations in the same script you risk ending<br />

up with parse errors. In this book, we will use double quotes in JavaScript programs.<br />

Finally, you populate myDivElement by adding the HTML code you built in the string variable:<br />

36<br />

}<br />

// add content to the element<br />

myDiv.innerHTML = string;<br />

In this example, you have used the innerHTML property of the DOM to add the composed HTML<br />

to your document.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!