eire web design home page contact eire-web design eire web design and development site map
stepping on in business
• Welcome to Eire Web Design Ireland

Archive for the ‘Ajax’ Category

Dependent Select Box using Ajax

Tuesday, November 13th, 2007

One of the members on Irish WebMaster Forums asked for help in creating a simple dependent select menu and the most obvious option is by using Ajax, so I decided to put up this post with step-by-step instructions.

First, create a new PHP page (as we are going to use php for this) and name it “page1.php“.

On this page we are going to add the following javascript code, which will take care of our XMLHTTP request.

<script type="text/javascript" language="javascript">   

var ewd_domain = 'http://www.eire-webdesign.ie/'; //set domain   

var ewd_loading_img = ewd_domain + 'images/loading.gif';//set image path   

var ewd_loading_msg = 'Loading Data…';//set loading message   

var xmlhttp_obj = false;
//create the XMLHttpRequest
function ewd_xmlhttp(){   

 if (window.XMLHttpRequest){ // if Mozilla, Safari etc   

  xmlhttp_obj = new XMLHttpRequest();   

 }else if (window.ActiveXObject){ // if IE   

  try{   

   xmlhttp_obj = new ActiveXObject("Msxml2.XMLHTTP");   

  }catch (e){   

   try{   

    xmlhttp_obj = new ActiveXObject("Microsoft.XMLHTTP");   

   }catch (e){   

   }   

  }   

 }else{   

  xmlhttp_obj = false;   

 }   

 return xmlhttp_obj;   

}   //get content via GET   

function ewd_getcontent(url, containerid){   

 var xmlhttp_obj = ewd_xmlhttp();   

 document.getElementById(containerid).innerHTML = '<img src="' + ewd_loading_img + '" />' + ewd_loading_msg;   

 xmlhttp_obj.onreadystatechange=function(){   

         ewd_loadpage(xmlhttp_obj, containerid);   

         }   

 xmlhttp_obj.open('GET', url, true);   

 xmlhttp_obj.send(null);   

}        

function ewd_loadpage(xmlhttp_obj, containerid){   

 if ( xmlhttp_obj.readyState == 4 && xmlhttp_obj.status == 200 ){   

  document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;   

 }   

}      

Now will create a simple form with two select menus and a submit button:

<form name="select_m" id="select_m" action="<?php echo $_SERVER['REQUEST_URI']."?".$_SERVER['QUERY_STRING'];?>" method="get">      

<select name="sel1" id="sel1" onchange="ewd_getcontent('page2.php?sel1='+this.value, 'span1');">   

    <option value="">select...</option>   

    <option value="1">first</option>    <option value="2">second</option>   

    <option value="3">third</option>   

   </select>   

   <span id="span1">   

   <?php   

   include_once("_page2.php");    

   //this is the page that will create the second select menu   

   ?>      

   </span>   

   <input type="submit" name="submit" id="submit" value="Go..." />     

  </form>

Now save page1.php and create a new page “page2.php“, where we are going to create the second select menu which will change its options based on the GET request:

<?php   

$txt = "";   

$qs = $_GET['sel1'] != "" ? preg_replace("#[^0-9]#","",$_GET['sel1']) : "1";//I use preg_replace to sanitze the get request   

//which in this case must be numbers   

//this is manually created but it can be easily populated from a database   

if($qs != ""){   

 if($qs == "1"){   

  $txt .= "<select name='sel2' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='11'>first-first</option>   

     <option value='12'>first-second</option>   

     <option value='13'>first-third</option>   

    </select>";   

 }elseif($qs == "2"){   

  $txt .= "<select name='sel2' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='21'>second-first</option>   

     <option value='22'>second-second</option>   

     <option value='23'>second-third</option>   

    </select>";    

 }elseif($qs == "3"){   

  $txt .= "<select name='sel' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='31'>third-first</option>   

     <option value='32'>third-second</option>   

     <option value='33'>third-third</option>   

    </select>";    

 }   

 echo $txt;   

}   

?>

Save the second page, and using your preferred browser navigate to “page1.php”, make a selection and see how the second menu will change its values.

How it works? Simple.
We have the javascript code that will take care of our XMLHttpRequest.
As you have noticed we have added a span id html element that will hold our second select menu, which is passed to the Ajax code to replace its content with the html received from the “page2.php” using the innerHTML function:

............
document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;
............

We’ve added “onchange” function to the first select menu that will execute our javascript function, passing its value to the the second select menu for filtering the data, and also the span id to tell the function where the magic has to be executed.
Just in case javascript is disabled in the user browser, we’ve added a submit button as well so the form is still functional.

Few minutes of work and voila you’ve done it.
It wasn’t that hard was it?

You can see an working example here: Dependent select menus

Ajax link and search engines friendly URLs

Wednesday, November 7th, 2007

Ajax technology, everyone is talking about it, but it has it’s own drawback.
Few advantages for using Ajax on your website:

1. Better and more responsive website and web applications.
2. It uses existing technology that are available in most browsers.
3. It can be use with any server-side language (ASP, PHP) + JavaScript, already in use by many web developers.
4. Ajax integrates perfectly with existing designs and website functionality.
5. Enables immediate tasks like server-side form validation without refreshing the page.
6. Creating simple suggest functionality like Google Suggest.

plus a lot more…

Some of the disadvantages using Ajax:

1. Because pages does not change while it still brings new content or checking a form, can not be easily bookmarked.
2. Search engines may not be able to index all pages available on your website.
3. Back button in browsers doesn’t work as with a normal page.
4. Javascript can be disabled in some browsers client-side making your application non-functional.

Today we will be discussing the solution for creating friendly URLs, using Ajax technology while keeping the functionality for users that have Javascript disabled, and also allow search engines to index your page content as well.

So lets go ahead.
A standard link to another page normally looks like this:

text

while an Ajax link is formatted as below:

text

The problem with the Ajax formated link is that search engine can not follow it and if javascript is disabled on the client-side, the link is useless.
A simple way to make the link working no matter what, is by creating a new page that will include your content you were going to load into the existing page, and change your link structure as in the example below:

text

Adding “return false;” to the “onclick”, if javascript is enabled, the browser will fetch the content into the page section specified without refresh, but if javascript is not available the user will be brought to the new page you just created.

This is just one of the solutions available to make sure you keep the functionality of your website, search engines will index your content, and having a responsive web applications where Javascript available.

Good luck!

Ajax load content from another file using POST or GET

Monday, October 15th, 2007

These is a simple Ajax example that will load content into the page from another file without browser refresh.
05-Oct-2007 – We have updated the javascript to allow the use of forms to be submited using POST.

Click here for Demo » OR DOWNLOAD THE AJAX SAMPLE

How does it work?

First we need to create the javascript file with the following code:

var ewd_domain = 'http://www.eire-webdesign.ie/'; //set domain
var ewd_loading_img = ewd_domain + 'images/loading.gif';//set image path
var ewd_loading_msg = 'Loading Data...';//set loading message
var xmlhttp_obj = false;       

//create the XMLHttpRequest
function ewd_xmlhttp(){
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
xmlhttp_obj = new XMLHttpRequest();
}else if (window.ActiveXObject){ // if IE
try{
xmlhttp_obj = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlhttp_obj = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
}
}    

}else{
xmlhttp_obj = false;
}
return xmlhttp_obj;
}    

//get content via GET
function ewd_getcontent(url, containerid){
var xmlhttp_obj = ewd_xmlhttp();
document.getElementById(containerid).innerHTML = '' + ewd_loading_msg;
xmlhttp_obj.onreadystatechange=function(){
ewd_loadpage(xmlhttp_obj, '', containerid);
}
xmlhttp_obj.open('GET', url, true);
xmlhttp_obj.send(null);
}       

function ewd_loadpage(xmlhttp_obj, content, containerid){
if ( xmlhttp_obj.readyState == 4 && xmlhttp_obj.status == 200 ){
document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;
}
}       

//functions for posted values from forms vis POST
function ewd_getcontent_post(url, content, containerid){
var xinput = content;
var xmlhttp_obj = ewd_xmlhttp();
document.getElementById(containerid).innerHTML = '' + ewd_loading_msg;
xmlhttp_obj.open('POST', url, true);
xmlhttp_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp_obj.onreadystatechange = function() {
ewd_loadpage(xmlhttp_obj, content, containerid);
}
xmlhttp_obj.send(content);
}   

//convert form data sent to POST CONTENT
function ewd_submit_form(page_to,form_name,containerid) {
var content = ewd_convertFormDataToPostContent(form_name);
ewd_getcontent_post(page_to, content, containerid);
}       

function ewd_convertFormDataToPostContent(form_y){
var f=document.getElementById(form_y);
var content_to_submit = '';
var form_element;
var last_element_name = '';
for (i = 0; i < f.elements.length; i++){
form_element = f.elements[i];
switch (form_element.type){
// text fields, hidden form elements
case 'text':
case 'hidden':
case 'password':
case 'textarea':
case 'select-one':
content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
break;
// radio buttons
case 'radio':
if (form_element.checked){
content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
}
break;
// checkboxes
case 'checkbox':
if (form_element.checked){
// Continuing multiple, same-name checkboxes
if (form_element.name == last_element_name){
// Strip of end ampersand if there is one
if (content_to_submit.lastIndexOf('&') == content_to_submit.length - 1){
content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
}
// Append value as comma-delimited string
content_to_submit += ',' + escape(form_element.value);
}else{
content_to_submit += form_element.name + '=' + escape(form_element.value);
}
content_to_submit += '&';
last_element_name = form_element.name;
}
break;
}//end switch
} //end for
// remove trailing separator
content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
return content_to_submit;
}

Now create the page that will hold the content to be displayed (“content_ajax.php”):

	First we create the link that "onclick" will populate the div or span id - "div_populate".
	Make sure you have the javascript source "ajax.js" included into this file.

	• Get Data 1 »
	  
	• Get Data 2 »
or you can use a form to submit data (using "onchange" on the form input or "onclick" on the submit button):
Now and example using a form to post the data Here is the place where the data from the "content_ajax.php" page will be displayed. © Eire-Web Design Ireland

This is the code for the file that will be called:

$datax = $_POST['test'];
$datax1 = $_POST['test1'];
$datax2 = $_POST['test2'];
if($datax != "" || $datax1 != "" ){
echo "data posted: " . ($datax != "" ? "first input = ".$datax : "").
($datax1 != "" ? "second input = ".$datax1 : "").
($datax2 != "" ? "checkbox input = ".$datax2 : "checkbox input = unchecked")."";
exit();
}       

$data = "1";
if(isset($_GET['data']) && $_GET['data'] != ""){
$data = $_GET['data'];
}
if($data =="1"){
?>
 Welcome to Web Design Dublin Ireland - Eire-WebDesign.ie   This is the second link
}elseif($data == "2"){ echo "This is the second data that has been sent using GET."; }elseif($data == "3"){ $datax = htmlspecialchars($_GET['test']); echo "data posted: " . $datax; } ?>

Ajax – can I use it or not?

Sunday, October 14th, 2007

Quote from Wikipedia:
 ”Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications.
  The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change.
  This is meant to increase the web page’s interactivity, speed, and usability. ”
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

A while back I was wondering how can I make use of this technology and still have the website accessible by visitors that doesn’t have JavaScript enabled browser and can not make use of the XMLHttpRequest and also have the search engine spidering the website without any problems.

The solution I came up with was to create an instance of the XMLHttpRequest and store a cookie on the user computer with the value received.
If the instance is successfully created we store a cookie “xml_state” with the value “yes” for 1 day (24 hours), if not then a cookie “xml_state” with the value “no” will be set instead.
Then using the request cookie method we can handle how we are writing the “a href” tags.
I have this done using PHP, by creating another function to handle the way the links will be written.

Let’s dig in step by step.

// first create the XMLHTTP function
// Create XMLHTTP - Note: AJAX feature requires IE5.5+, FF1+, and NS6.2+
function EWD_createXMLHttp() {
if (!(document.getElementsByTagName || document.all))
  return;
  var ewd_ret= null;
  try {
    ewd_ret = new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
    try {
      ewd_ret = new ActiveXObject('Microsoft.XMLHTTP');
   } catch (ee) {
  ewd_ret = null;
  }
}
if (!ewd_ret && typeof XMLHttpRequest != 'undefined')
  ewd_ret = new XMLHttpRequest();
  return ewd_ret;
}

second will create the function that will handle the cookie

function EWD_SetCookie(cookieName,cookieValue,nDays) {
  var today = new Date();
  var expire = new Date();
  if (nDays==null || nDays==0) nDays=1;
  //we set the cookie to one day just in case the visitors decides to make changes to the browser
  expire.setTime(today.getTime() + 3600000*24*nDays);
  document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
//end of set cookie     

//check for XMLHTTP support
var xmlHttp = EWD_createXMLHttp();
if (xmlHttp){
  EWD_SetCookie("xml_state","yes",1);
}else{
  EWD_SetCookie("xml_state","no",1);
}
//end of check for XMLHTTP

this is the php function that will handle the cookie state and create the url

function link_url($url_link,$div_name){
  if(@$_COOKIE['xml_state'] == "yes") {
    //we can use ajax
    $url_link = '$url_link' onclick='ajax_function_that_will_make_the_request($url_link, $div_name); return false;'
    return $url_link; //return ajax type a href
  }else{
    return $url_link; //return normal a href
  }
}

then on the page you will be using the above function to handle how the a href tag are written to the page:

link_url($url_link,$div_name)
Links...

Chicklets...
  • http://www.eire-webdesign.ie/blog/feed/
    http://www.eire-webdesign.ie/blog/feed/
    Google Reader or Homepage
    Add to My Yahoo!
    Subscribe with Bloglines
    Subscribe in NewsGator Online
    add to msn
    Add to My AOL
    Add to Technorati Favorites!
    pageflakes
    windows live