Home > AJAX, Tutorials > Submit a Form Using AJAX

Submit a Form Using AJAX

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
  1. No comments yet.
  1. No trackbacks yet.