New Posts

Friday, May 20, 2011

Ajax 101

Asycnronous Javascript And XML, the mysterious entity known as AJAX.

What is it? What does it do? In simple terms its a method of connecting a website to a server side script without needing to submit a form, or reload a page.

For years the usual way of getting data from the server was to submit a form with values to be processed by the server which would in turn return the results of its process. This usually slowed down websites considerably, and there was no real time interaction between the user and the website.

Ajax solves this by opening a direct connection to the server, and requesting the data processing without needing to submit a form.

Ajax is composed of 3 main sections:
  • The Javascript that executes the Ajax call
  • The Ajax that calls the server side script
  • The Server side Script that takes the parameters and produces the data to be returned to the website.



The main component of AJAX is the XMLHttpRequest object. This thing does it all. It opens the connection, waits for the results, and then makes them available to JS for any further parsing or usage.

But before we can use that we need our Server Side process. This can be pretty much any script that returns data, and it can be done in pretty much any language the server can execute. PHP, ASP, Coldfusion etc...

For our example we'll be using PHP.

The Server Side Script

The Server Side Script has one important task to accomplish, and that is to produce the results we need. The script should be designed like any server side script, except we don't need full html tags as we are going to deliver this to our Javascript layer for usage in an already established page.

So basically all we want is for our script to output our data. We could include a table structure or some other markup if we require, but only if we don't plan for your JS side to do anything to data, otherwise outputting in usable formats such as comma separated strings, or a JSON object is enough.

For our example script we'll just have a process that takes a value from the POST array and echoes it out in a string.

PHP Script


<?PHP

if(isset($_POST['id'])){

echo "The ID Passed is: $_POST[id]";

}

?>





Javascript and Ajax

No we need a way of calling our server side script, and getting back the results. to do this we will require the XMLHttpRequest object from the JS window object.

We start by defining our request object:

Request Object


var requestObj=new XMLHttpRequest();




We can now use our new object to initiate the call to our server side script. However before we can do that we'll need to make a decision. do we want our call to be synchronous or asynchronous. A synchronous call means the Js stops and waits for the server to complete the processing before continuing on, this effectively makes the website hang and be unresponsive until the call is finished. Ultimately we would only use this if don;t have lots of processing to do and the response would be returned rather quickly.

Otherwise we'll want to use the asynchronous method which as it implies lets the website and all JS functions continue to run while the server process is being executed. This allows the user to keep doing things while the request is under way.

We are going to go for the asynchronous method, so we need to
setup a function to handle the data once it returns. For this we use the onreadystatechange event of our ajax object. onreadystatechange triggers every time the the readystate property changes. The readystate property simply holds the status of our request. We want it to be 4 so the Request is complete. The other values are not relevant in the context of a webpage as you can't actually do anything about them.

We also have to check the status property. The value we want is 200, which stands for "O.K." that means the call to our server side script executed correctly and data was returned. Status has many values that you can check; most are the standard HTTP status codes like the classic 500 Internal Server Error, 404 Not found error etc...

We check for both those values, and if they are 4 and 200 we can proceed to use the responseText value to get whatever our script produced as output.

Request Object and Properties


requestObj.onreadystatechange=function()
{
if (requestObj.readyState==4 && xmlhttp.status==200)
{
var results=requestObj.responseText;
document.getElementByID('myDiv').innerHTML=results;
}
}




We can then use our results to populate anything we need using regular JS calls. In the example above I simply placed everything into a div.

The next part of our Ajax interaction is to call our actual script. We'll use the open() method to define our script address, the method we want to use, and the type of call (synch vs asynch) amongst other things.

The Open method


xmlhttp.open("POST","script.php",true);




The Methods are the same ones used in a From, GET or POST. POST is the better alternative if you plan on sending a lot of data to be processed.

The address of our script is the second value we need to set. the request object is limited to reading scripts form the same domain it originates so you can;t go out and read pages from other websites to mash up into your own site.

We then need to set up our headers. Since we are basically recreating the function of a form, we set it up as such.

Headers


requestObj.setRequestHeader("Content-type","application/x-www-form-urlencoded");




And finally we need to send our parameters to our server side script.

Send Paramters


xmlhttp.send("id=" + value + "&action=list");




The parameters will appear in our POST array inside our server side script. In the case of PHP the $_POST variable.

You can set a string, or you can add values from variables or both like above by using concatenation. "value" is a variable that contains the id we wish to pass. We separate each pair with an ampersand &

With that we are done, we can setup our ajax call to be executed when a button is pressed.

Button Call


Enter ID: <input type="text" id="idbox">

<input type="button" onclick="runAjax();">




With that done, inputing an ID and pressing the bun will run our Ajax function and in turn execute our PHP script without needing to reload the page.

In our next installment we'll be looking at a slightly more complex example, by getting data from a database on the fly.

Working Example





Download the example:

Questions? Comments? Use the comment form.

Wednesday, May 18, 2011

Common Validation Errors

In a previous post i talked about the importance of validation, but I never delved into what types of errors you would commonly encounter. Today we are going to take a look at 3 common errors you encounter when validating.


There is no attribute "xxxx"



Html elements or tags have attributes one can assign to them. things like a name, and ID, a class but sometimes we may try to use an attribute that an element doesn't have. Or an attribute it may have in one particular doctype but not in another.

For instance lets say we are building a form to get user input:

From Code

<form name="MyForm" action="mypage.php" method="POST">

<p>User:<input type="text" name="user"></p>

<p>Password:<input type="password" name="user"></p>

...

</form>



If I were using an XHTML strict doctype in the website that contained this, the error would be something like:


Line 7, Column 12: there is no attribute "name"
<form name="MyForm" action="mypage.php" method="POST">
You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element.


In <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> only input elements can have a name. Divs,paragraphs, links etc.. cannot have a name attribute.

Most would think a name is vital to be able to access form elements if you are using JS to validate the form. For XHTML Strict, you only need an ID for the element you wish to access through Javascript.


End tag for "xxxx" omitted, but OMITTAG NO was specified



This one of the more common mistakes simply because its the easiest to over look.

It happens on certain tags such as image, break and any other tag that doesn't require a closing tag to accompany it unlike other tags like divs, links, spans etc...

Closing Tags


<div></div>

<a></a>

<span></span>



----



Self Closing


<img src="">



<br>



<input type="text">




Self closing tags like above require an extra special character to properly close them. the forward slash. In XHTML strict these tags need to be terminated as .../> to be properly closed, otherwise they generate errors. Since Transitional doctypes don't require this, its easy to forget to add them at the end.



document type does not allow element "xxx" here; missing one of a, b, c,d,e,...



This error is more of a nitpicky error, Basically what is says is that whatever xxx is, it cannot be placed wherever it is you have it because it requires something else to contain it. The most common example of this are label tags. Most would assume you can simply add them in front of an input to add a text label to it. XHTML Strict doctypes will barf at it as they require the label to be inside a block level element such as a div or a paragraph.

Wrong


<form ...>

<label>My Label</label><input type="text">

</form>



Right


<form ...>

<p><label>My Label</label><input type="text"></p>

</form>





There are many more errors, some harder to understand than others, however its important to read the provided reasons for the error, as more often than not they contain vital clues to what may be wrong with that particular line.