Archive

Archive for the ‘AJAX’ Category

Submit a Form Using AJAX

March 6th, 2008 admin No comments

Introduction

After getting AJAX to work, a common follow-up task is to create a method for submitting a form via AJAX and displaying the response somewhere without changing the page. This can be done pretty simply with a little Javascript method that goes through the form, grabs all the inputs and attaches them to the URL that the AJAX request is sent to.

This one works quite well:



function doAjaxFormSubmit(formId, actionUrl, elemId) {
    var formVars = getFormVars(formId);
    if(actionUrl.indexOf("?") == -1) actionUrl += "?" + formVars;
        else actionUrl += "&" + formVars;
    doAjaxRequest(actionUrl, elemId);
}

function getFormVars(formId) {
    var theForm = document.getElementById(formId);
    var str = "";
    for(i=0; i< theForm.elements.length; i++)    {
        var elem = theForm.elements[i];
        if((elem.type == "radio" || elem.type=="checkbox") && !elem.checked) continue;
         str += elem.name + "=" + escape(elem.value) + "&";
    }
    return str;
}

The doAjaxFormSubmit() function uses the doAjaxRequest() function:


function doAjaxRequest(actionUrl, elemId) {

// MAKE NEW XMLHTTP OBJECT
    var xmlHttp=null
    try { // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest()
    }
    catch (e) { // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
        }
    }

    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request")
        return
    }

// WHAT TO DO WITH THE RESPONSE
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
            document.getElementById(elemId).innerHTML="processing, please wait..."
        }
        else if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
            document.getElementById(elemId).innerHTML=xmlHttp.responseText
        }
    }

// MAKE THE REQUEST
    xmlHttp.open("GET",actionUrl,true)
    xmlHttp.send(null)
}

The form also needs to be adjusted a little too. Instead of an input of type=”submit” for a submit button, we just use a type=”button” and add an event handler to onClick. See below:


<form id="myForm" >

    <!-- Your inputs here, make sure to include names -->

    <input type="button" name="submitButton" value="Submit"
        onClick="doAjaxFormSubmit('myForm', 'ajaxServerAction.php?action=readForm', 'formResponseData');" >

</form>

That’s about it. One thing to keep in mind is that with this method specifically, though you might be able to change this, all the input values are in the $_GET array on the server side, since we simply manually embed them into the URL of the request URL. I usually like to send my forms via the POST method, so it’s something you need to keep in mind as far as security is concerned.

Categories: AJAX, Tutorials

The Simplest AJAX Tutorial Ever

March 6th, 2008 admin No comments

Introduction

AJAX is a method of getting information from the server without reloading the whole page. The Javascript XMLHttpRequest object (or in Internet Explorer, the ActiveXObject) is used to make a call to a given URL in the background and then do something with the response data. In this example we simply populate the innerHTML of <div id=’suppliedId’ > with the response data.

Click here for an example

What’s Needed

These elements are needed:

  • Something to trigger the request. In this example we use a simple <a> tag with an onClick to trigger the request
  • The necessary Javascript tools to create the xmlHttp object, make the request, and do something with the response data
  • Something on the server to get. This is where the interesting stuff goes – a query or whatever it is that’s on the server and that you want to access with AJAX

Putting It Together

Let’s start with the Javascript. I’ve condensed everything into one function for illustrative purposes. The onClick event in our hyperlink (below) will call the doAjaxRequest() function which:

  1. creates the xmlHttp object, then
  2. defines what to do with the response data (put it in the HTML element with the supplied id), and finally
  3. makes the call to the supplied URL. It needs two arguments:
    1. actionUrl is the file on the server that you are requesting
    2. in this example we are simply putting the response data into a div, so we need an id to identify it – elemId.

The link to trigger the request looks like this:

<a href="javascript:;" onClick="doAjaxRequest('ajaxServerAction.php?action=displaySimpleMessage', 'responseDiv');">Click Here to trigger an AJAX request</a>

And the Javascript function like this:


function doAjaxRequest(actionUrl, elemId) {

// MAKE NEW XMLHTTP OBJECT
   var xmlHttp=null
   try { // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest()
   }
   catch (e) { // Internet Explorer
      try {
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
      }
      catch (e) {
         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
      }
   }

   if (xmlHttp==null) {
      alert ("Browser does not support HTTP Request")
      return
   }

// WHAT TO DO WITH THE RESPONSE
   xmlHttp.onreadystatechange=function() {
      if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
         document.getElementById(elemId).innerHTML="processing, please wait..."
      }
      else if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
         document.getElementById(elemId).innerHTML=xmlHttp.responseText
      }
   }

// MAKE THE REQUEST
   xmlHttp.open("GET",actionUrl,true)
   xmlHttp.send(null)
}

Advanced Techniques

There is a lot of potential in this technique. Any Javascript event can trigger the Ajax request, even onLoad or onMouseOver or onMouseOut. Imagine the amount of web analytics data that could be collected! Or loops can wait 5 seconds or whatever and continually ask for updates.
Also, you can get creative with what is done when the response is received (display an appropriate notification) or what to do with the response data. XMLHttpObjects response data can be accessed as responseXML instead of responseText and then parsed however you like.

Categories: AJAX, Beginner, Tutorials