Wednesday, July 15, 2009

Asynchronousity vs. Synchronousity in AJAX

Sometimes it is necessary to halt script execution until an ajax request has successfully returned and handled data it processes.

By default, your script will be executed one line after the other (asynchronously) while running the ajax process in the background. This means that after you make your ajax call, the script moves right on to the next line while your ajax call executes in the background eventually calling its own success function when data is returned.

Let's say your script depends on processed data from an ajax call that happens prior to your use of another function or conditional test. In this case, you will most likely want to halt the further execution of your script until after the ajax call has completed. This will insure that you get the data you're expecting and not spending hours debugging and banging your head on a wall.

The fix is extremely simple in jQuery. Let's take a look...


function asyncAjaxCall(e){

var hasChanged = 0;

$.ajax({

type:"POST",

url:"myapp.php",

data:"d=" + e,

dataType:"text",

success:function(data){

if(data == "changed"){

hasChanged = 1;

}

}

)};



if(hasChanged){ doThis(); }

else{ doThat(); }

}


In the above example, asynchronicity is assumed and try as you may, only the doThat function will be called because immediately after executing your ajax statement, the function begins to execute your conditional statement. Because your ajax success statement hasn't finished its execution, the data returned will be processed after your script has finished execution and hasChanged has not been handled as you might have expected.

To prevent this, we need to disable the asynchronous behavior of the ajax call to make sure that the script doesn't do anything before we have had a chance to process the data returned. The function below will take care of that...


function syncAjaxCall(e){

var hasChanged = 0;

$.ajax({

async:false,

type:"POST",

url:"myapp.php",

data:"d=" + e,

dataType:"text",

success:function(data){

if(data == "changed"){

hasChanged = 1;

}

}

)};



if(hasChanged){ doThis(); }

else{ doThat(); }

}


By default, async is true when you make a call with a jQuery ajax statement. By setting async to false, we force the function to wait until after the ajax's success event has had a chance to do something with our data giving us a chance to use that information later in our conditional statement.

Thursday, July 9, 2009

Dynamic Content Using jQuery, AJAX and PHP

A friend recently asked me to help him update his aging portfolio. In its first inception, the portfolio had used Flash and other technologies to spark interest from potential web design firms looking for a graphic artist. This time around though, he wanted to use a singular layout and design that would change only when and where necessary. I immediately thought AJAX.

Many sites today use AJAX for a variety of different things but one of the most common is to dynamically change the content on a given page based on user input. There are various different AJAX frameworks out there that can do this...script.aculo.us, jQuery, mooTools just to name a few. I personally prefer jQuery in combination with PHP mostly because of familiarity but to each his own.

The basic concept is simple...
  • User provides input usually via interaction with the site such as clicking a link
  • The action calls a javascript function that makes an AJAX call to a server side program
  • Based on the interaction, our server side program will be responsible for sending content back to the AJAX function.
  • The AJAX function executes 'success' code that updates/changes content on the page based on what was returned by the server side program.
In my friends case, he wanted to pull in content from other html pages and display them when a visitor clicked on the navigation links on his pages. First, each navigation link was setup to call the soon to be written AJAX function very similar to this...

<a href="javascript:updateLiveContent('photos');">My Navigation Link</a>

Next, I wrote the Javascript function that was responsible for making the Ajax call using the jQuery framework.

function updateLiveContent(page){
$.ajax({
type:"POST",
url:"updateLiveContent.php",
data:"page=" + page,
cache:false,
dataType:"text",
success: function(data){
$("#content").html(data);
}
});
}

The function makes an ajax call using an $.ajax initializer. The important parts here are
  • url - Tells the ajax object which document on the server to request and send data to
  • data - The query string to send to the document defined by url
  • dataType - The type of data you will be returning from your server side application
  • success - The function that will process and update all page content
The ajax object immediately calls the document given by url (in our case updateLiveContent.php) and waits for any data that might be returned by the server side application. Let's look at updateLiveContent.php...

<?php
$template = $_REQUEST["page"];
$siteUrl = "http://www.mywebsite.com/";
$html = file_get_contents($siteUrl . $template . ".html");
echo $html;
?>


Our PHP file requests the page variable from our ajax call and then gets the contents of an html file based on the siteUrl and template variables. After it has pulled the content in, it simply echos it out right back to the ajax script. Our ajax object then fires its success event which proceeds to change the inner html of a div that has an id of content.

Late Night Humor

A search for new wallpaper for my G1 gave me one of the best laughs I've had in good long while. Priceless!

Wednesday, July 8, 2009

Great Usability

One of the greatest marks of a great web 2.0 site is they not only make their sites highly usable but they also make it easy to use while on the go! Congrats to twitter and google for making my life easier.

Mobile Blogging Easy As 1-2-3

A simple post to show that posting from an Android enabled device is as simple as sending an SMS message.