Using ajax to submit HTML form without page refresh.

  • 31-08-2018
  • web_development
Thumb

Share:

https://techconductor.com/blogs/web_development/submit_ajax_form_without_page_refresh.php

Copy


Gone are those days when submitting a form required the page containing the form to refresh. Now all the hard work is done by jquery ajax. AJAX means Asynchronous JavaScript And XML.

AJAX works in the following ways: It first gathers the data to be submitted and the location of the backend file where it will submit the form data. AJAX can handle both POST and GET request.

One of the most important feature of ajax is its .done() function which holds the data response from the backend after submitting the form.

So to sum up we will make a simple contact form and then use ajax to submit the form without refreshing the page. We will use the HTML form id to identify the form and gather its data.

The HTML part :

Here is the simple HTML form we will be using.



Make sure all the input field has the proper attribute name and id.

The PHP part :

For the backend we will use simple PHP script to process and validate the data. Here is the code which just checks for the empty field and responses with success being true or false.

<?php
ob_start();
session_start();

$errors = array();
$data = array();

function validate($v)
{
  if(empty($v)) {
    return false;
  } else {
    $ok_v= strip_tags(trim($v));
    return $ok_v;
  }
}

if(isset($_POST['submit'])){
  $name = validate($_POST['name']);
  $email = validate($_POST['query']);
  if($name && $email){
    $data['success'] = true;
    $data['response'] = 'form ok';
  }else{
    $errors['failed'] = 'Oops! please try again!';
    $data['success'] = false;
    $data['errors'] = $errors;
  }
}else{
  $errors['failed'] = 'Oops! please try again!';
  $data['success'] = false;
  $data['errors'] = $errors;
}

header('Content-Type: application/json');
echo json_encode($data);
?>

The JavaScript part :

Here is the JavaScript code to submit the form and read the response from the backend.



The entire main JavaScript code is wrapped inside the jquery ready function which makes sure that our code only runs when the entire page is loaded. Next is the submit function which gets called when submit button which is inside the HTML form is clicked.

event.preventDefault() is used so that the page dosen't refresh or follows the backend file location.

Next we just disabled the submit button. The FormData variable holds all the data from the form and one additional data is also concatenated.

Now we provide the ajax with all the options and then inside the .done() function we examine the data response from the backend. Here we can do whatever we want to do validate, authorize, etc.