Simple way to create an AJAX Form using Pure JavaScript without jQuery. AJAX form tutorial & example, live demo & download example.

How to Create an AJAX Form without jQuery

We need to XMLHttpRequest() class and FormData() class, with some functions. We will create an AJAX form in easy way with example.

Live Demo and Download

Try live demo, or download the example.

Create an AJAX Form

JavaScript function:

/*
    AJAX in Pure JavaScript, without jQuery.
    Written by Qassim Hassan | https://wp-time.com/ajax-form-pure-javascript-without-jquery/
*/

/* AJAX Function */
function AJAXform( formID, buttonID, resultID, formMethod = 'post' ){
    var selectForm = document.getElementById(formID); // Select the form by ID.
    var selectButton = document.getElementById(buttonID); // Select the button by ID.
    var selectResult = document.getElementById(resultID); // Select result element by ID.
    var formAction = document.getElementById(formID).getAttribute('action'); // Get the form action.
    var formInputs = document.getElementById(formID).querySelectorAll("input"); // Get the form inputs.

    function XMLhttp(){
        var httpRequest = new XMLHttpRequest();
        var formData = new FormData();

        for( var i=0; i < formInputs.length; i++ ){
            formData.append(formInputs[i].name, formInputs[i].value); // Add all inputs inside formData().
        }

        httpRequest.onreadystatechange = function(){
            if ( this.readyState == 4 && this.status == 200 ) {
                selectResult.innerHTML = this.responseText; // Display the result inside result element.
            }
        };

        httpRequest.open(formMethod, formAction);
        httpRequest.send(formData);
    }

    selectButton.onclick = function(){ // If clicked on the button.
        XMLhttp();
    }

    selectForm.onsubmit = function(){ // Prevent page refresh
        return false;
    }
}

HTML form:

<form action="form.php" id="my-form">
    <input type="text" name="some-name" value="">
    <input type="submit" name="submit" value="Send me!" id="my-button">
</form>
<div id="my-result"></div>

form.php file:

<?php
    if( isset($_POST['some-name']) and !empty($_POST['some-name']) ){
        echo $_POST['some-name'];
        exit();
    }
    else{
        echo 'Please enter your name!';
        exit();
    }
?>

Now add this code in your HTML page or in JavaScript file:

<script type="text/javascript">
    /* Usage */
    window.onload = function (){
        AJAXform( 'my-form', 'my-button', 'my-result', 'post' );
    };
</script>

Parameters: AJAXform( ‘your-form-id‘, ‘button-id‘, ‘result-element-id‘, ‘post or get method’ );

Check more AJAX tutorials.