Ajax Form Submission

by Ryan Morris

HTML

<div id="form">
    <form>
        <input name="first" placeholder="First Name"/>
        <input name="last" placeholder="Last Name"/>
    </form>
</div>
<button id="form-serialize">Form serialize</button>
<button id="form-submit">Form submit</button>

<div id="container"></div>

JavaScript

(function () {
    
    var httpRequest;
    
    document.getElementById("form-serialize").onclick = function () {
       getData("#form form");
    };
    
    document.getElementById("form-submit").onclick = function () {
        makeRequest('/echo/json/');
    };

    function makeRequest(url) {
        
        console.log("Beginning makeRequest");
        
        // 1) first create the Request object
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            
            httpRequest = new XMLHttpRequest();
            
        } else if (window.ActiveXObject) { // IE
            
            try {
                
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                
            } catch (e) {
                
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        
        // 2) Tell it how to handle the response
        httpRequest.onreadystatechange = alertContents;
        
        // 3) initiate the request
        httpRequest.open('POST', url, true);
        
        // 4) Set any headers
        httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        
        // 5) Submit the request
        httpRequest.send(getData("#form form"));
    }
    
    function getData(form_selector) {
     
        console.log("running getData");
        
        var form = document.querySelector(form_selector);
        
        // serialize form data into a key=value string
        // going to cheat here...
        var serializedData = Ext.Ajax.serializeForm(form);
        console.log(serializedData);
        
        // could also:
        // serialize a json object
        var stringifiedJson = JSON.stringify({
            first_name:...