Home > Back-end >  Form validation and Ajax - Vanilla JS
Form validation and Ajax - Vanilla JS

Time:09-25

I have form that has to be validated before submitting and notification should be shown with error without reloading the page.

Form code:

<button name="save" type="submit" form="product_form">Save</button>             
    <div>
        <form id="product_form" method="POST"">
            <label for="sku">SKU: </label>
            <input type="text" name="sku" id="sku" required><br>
            <label for="name">Name: </label>
            <input type="text" name="name" id="name" required><br>
            <label for="price">Price: </label>
            <input type="text" name="price" id="price" required><br>    
    </div>
    </form>
    <div id="validaton"></div>

I did validation in another validateData.php :

    <?php
    
    include __DIR__ . "/connectQuery.php";
    $sku=$_POST["sku"];
    $name=$_POST["name"];
    $price=$_POST["price"];
    
    $data = $query->getAllProducts();
    $objectMap = new ObjectMap($data);
    $productsArray = $objectMap->getAllProducts();
    $skuError="";
    $priceError="";
    $dataError="";
    // SKU validation 
    foreach($productsArray as $product)
    {
        if($product->getSku()==$sku)
        {
           $skuError="Your SKU is not unique!";
        }
    
    }
    echo $skuError;
    
    //Price validation
    if (!is_numeric($price))
    {
        $priceError = "Please enter valid data for price!";
    }
    echo $priceError;

//if there is no error 
if($priceError!="" && $skuError !="")
{

 header("Location: index.php");
}

So, my idea was to when I submit form, it calls this validateData.php, checks value, if there is error, echoes the error, and if not then redirect to index.php and it works, but I can't show those error messages without reloading page, so I guess I need to use ajax. I tried to write it:

function validateData(form){
 var xhr =  new XMLHttpRequest();
    xhr.onreadystatechange= function()
    {
        if(this.status==200 && this.readyState==4)
        {
           document.getElementById("validation").innerHTML = this.responseText; 
        }

    }
  
    xhr.open("POST","/partial/validateData.php");
    xhr.send();

  }

So, my questions are:

  • Do I use in html form onsubmit="validateData(this)" to reach ajax?
  • How to stop form from reloading page after submit? I found some solutions on net, but they are all in JQuery and I need Vanilla JS.
  • How to reach those input values from form in ajax, so I can send them via xhr.open("POST");

If there is easier way to do, I am open to listen, as I said, I need to check data, and if it is not valid show errors without reloading page. I am sorry for long post and questions, I am new to this concept.

CodePudding user response:

You can do something like this.

<?php
    
    include __DIR__ . "/connectQuery.php";
    $sku=$_POST["sku"];
    $name=$_POST["name"];
    $price=$_POST["price"];
    
    $data = $query->getAllProducts();
    $objectMap = new ObjectMap($data);
    $productsArray = $objectMap->getAllProducts();
    $skuError="";
    $priceError="";
    $dataError="";
    // SKU validation 
    foreach($productsArray as $product)
    {
        if($product->getSku()==$sku)
        {
           $skuError="Your SKU is not unique!";
        }
    
    }
    echo $skuError;
    
    //Price validation
    if (!is_numeric($price))
    {
        $priceError = "Please enter valid data for price!";
    }
    echo $priceError;

//if there is no error 
if($priceError!="" && $skuError !="")
{
 echo "noerror";
 //header("Location: index.php");
}

Javascript

function validateData(form){
 var xhr =  new XMLHttpRequest();
    xhr.onreadystatechange= function()
    {
        if(this.status==200 && this.readyState==4)
        {
           if(this.responseText === 'noerror') location.replace("index.php");
           else document.getElementById("validation").innerHTML = this.responseText; 
        }

    }
  
    xhr.open("POST","/partial/validateData.php");
    xhr.send();

  }

For form getting submitted, you can use type='button' instead of type='submit' easy fix.

For any queries comment down.

  • Related