AJAX Post Implementation in Pure Javascript

73,642

Yes and of course that's possible :)

<form action="request.php" id="register_form">
  <input class='formVal' type="text" name="first_name" placeholder="First Name">
  <input class='formVal' type="text" name="last_name" placeholder="LastName">
  <input type="submit" value="submit_now" onclick="myFunction(); return false;">
</form>

JS

function myFunction()
{
    var elements = document.getElementsByClassName("formVal");
    var formData = new FormData(); 
    for(var i=0; i<elements.length; i++)
    {
        formData.append(elements[i].name, elements[i].value);
    }
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                alert(xmlHttp.responseText);
            }
        }
        xmlHttp.open("post", "server.php"); 
        xmlHttp.send(formData); 
}

server.php

<?php
   $firstName = $_POST["first_name"];
   $lastName = $_POST["last_name"];
   echo $firstName." ".$lastName;
   //enter name and lastname into your form and onclick they will be alerted 
?>

Explanation: Function takes form elements by their class names and stores them in array. Then we create FormData object and loop through elements array for each element and append their name and value to FormData object. After that we create XMLHttpRequest() object that monitors state and status change during request and also sends data with post method to server.php When it's over and readystate equals to 4 and status equals to 200, we alert response from server.php, that we save in responseText attribute of XMLHttpRequest object.

Share:
73,642
Fariz Luqman
Author by

Fariz Luqman

My Github profile: https://github.com/farizluqman Visit my website: https://farizluqman.com

Updated on July 24, 2022

Comments

  • Fariz Luqman
    Fariz Luqman almost 2 years

    is there any implementation of AJAX Post in Pure Javascript (maybe using xmlhttprequest)?

    For example if I have a form like this:

    <form action="request.php" id="register_form">
      <input type="text" name="first_name" placeholder="First Name">
      <input type="text" name="last_name" placeholder="LastName">
      <input type="submit" value="submit_now">
    </form>
    

    and this is my implementation of the AJAX in jQuery

    $('#register_form').submit(function(e) {
    
    var postData = $(this).serializeArray();
    var formURL = $(this).attr("action");
    
    /* start ajax submission process */
    $.ajax({
        url: formURL,
        type: "POST",
        data: postData,
        success: function(data, textStatus, jqXHR) {
            alert('Success!');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Error occurred!');
        }
    
    });
    
    e.preventDefault(); //STOP default action
    
    /* ends ajax submission process */
    
    });
    

    Can I do the same WITHOUT the use of jQuery? If it is possible, how can I implement the above jQuery code into pure/plain Javascript code?