Form submit using AJAX

What is AJAX?
AJAX = Asynchronous JavaScript and XML.

How AJAX works?
Browser set an event and send HttpRequest to the server, where a request is processed and send data back to the browser, the browser will process on the data.

Who uses AJAX?
AJAX  uses a combination of:
1. XMLHttpRequest object (to exchange data asynchronously with a server)
2. JavaScript/DOM (to display/interact with the information)
3. CSS (style the data)
4. XML (often used this format for transferring data)

Google Suggests
AJAX was made popular in 2005 by Google, with Google Suggest.
Google Suggest is using AJAX to create a very dynamic web interface:
When you start typing in Google’s search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.

Let’s start
1. First, make one HTML form


<form>
   First name: <input type="text" onkeyup="showHint(this.value)">//function call on keypup for ajax request
   </form>
   <p>Suggestions: <span id="txtHint"></span></p>//This div is where we want to show suggestions that comes from ajax request

2.  Set event
If you are using AJAX with javascript and PHP

function showHint(str){
   var xhttp = new XMLHttpRequest(); // Create an XMLHttpRequest object
   xhttp.onreadystatechange = function() {// Create the function to be executed when the server response is ready
       if (this.readyState == 4 && this.status == 200) { // This means Php file send success
        document.getElementById("txtHint").innerHTML = this.responseText;// Data is given to div for display purpose(You can do various tricks in this portion after getting data)
       }
    };
}

There are two types of methods which send a request for PHP. One is GET and the other one is POST.
If you are using the GET method use below code.


xmlhttp.open("GET", "gethint.php?q=" + str, true);// Send the request off to a PHP file (gethint.php) on the server

If you are using POST method

xhttp.open("POST", "ajax_test.asp", true);
       xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       xhttp.send('"q=" + str')
    xmlhttp.send();

If you are using AJAX with jquery and PHP
If you are using GET

function showHint(str){
    $.get("gethint.php?q=" + str, function(data, status){
        alert("Data: " + data + "\nStatus: " + status);// this will display from PHP file
    });
}

If you are using POST

Function showHint(str){
           $.post("gethint.php",
             {
               q: str,
             },
          function(data, status){
               alert("Data: " + data + "\nStatus: " + status);//this will display from PHP file
           });
}

Alternative method


function showHint(str){
        $.ajax({
           url: 'gethint.php',
           data: {q: str}, // Data which u want to pass to PHP file
           type: 'post',(Defines the method which use)
           cache: false, // This means its not store cache
           success: function(output) {
             // Here you can perform operations with data
           }
         });
}

Parameters: The list of values are given below which we can use in above methods:
type: It is used to define the type of request.
url: It is used to define the URL where we want to send the request to.
username: It is used to define username that used in an HTTP access authentication request.
xhr: It is for creating the XMLHttpRequest object.
async: It’s flag which default value is true than it indicates whether the request should be handled asynchronous or not.
beforeSend(xhr): this function is run before the request is being sent.
dataType: Server response.error(xhr, status, error): It is used to run if the request fails or error
global: It’s default value is true. It trigger global AJAX event handles for the request.
ifModified: It’s default value is false. The request is only successful if the response has changed since the last request.
jsonp: String overriding the callback function in a jsonp request.
jsonpCallback: It is specify a name for the callback function in a jsonp request.
cache: It’s default value is true. It specify whether the browser should cache the requested pages.
complete(xhr, status): It shows the status of the request is being finished.
contentType: It’s default value is: “application/x-www-form-urlencoded” for data send to the server.
context: It’s specify the “this” value for all AJAX related callback functions.
data: It is used to specify data to be sent to the server.
dataFilter(data, type): It handles the raw response data of the XMLHttpRequest.
password: It specify a password to be used in an HTTP access authentication request.
processData: It’s default value is true. It is used to specify whether or not data sent with the request should be converted into a query string.
scriptCharset: It’s specify the charset for the request.
success(result, status, xhr): It’s run when the request succeeds.
timeout: It is the local timeout for the request.
traditional: It is used to specify whether or not to use the traditional style of param serialization.

PHP file

$term = $_REQUEST['q']; //Get variable which is sent from AJAX event
   $response = array();
   if($term!=''){
       //perform various operations with varible
       $response['message'] = array('Success'); 
       $response['code'] = '200';
       // Use above code and message for success response
   }else{
       $response['code'] = '401';
       $response['message'] = array('No results found');
       //Use above code and message for error or fail response
   }
echo json_encode($response); // Always return data in json format from php file