Ajax With Forms in PHP


I am using a form with Ajax in PHP. We use data added in a form to send to a script on the server, specified in the "action" in the "<form>" tag with Ajax, the form of the data can be sent with both the GET and POST methods. However, considering that with the GET method the content that can be sent is limited and forms can have a large amount of data, especially if you use a "textarea" for the message box, it is preferable to use the POST method. The process of sending data from forms using Ajax is similar to the examples presented in previous lessons, the difference is given by the way of getting the data.


Using name attributes

var get_data = document.formName.fieldName.value;

  • The formname attribute add In the in the <form> tag.

  • The fieldName value added in the name attribute in field.

Using Id Attribute


var get_data = document.getElementById(fieldID).value;

  • fielded is the value of ID attribute added in that field.

    Here's we will use a simple example of Ajax script can get data from a form, form sends a message in PHP script and then responds to a program. 


Create a PHP file on the server named "codel.php" and add the following code into it:



<title>Ajax and Form</title>

<script type="text/javascript">

    // create the XMLHttpRequest object

    function get_XmlHttp() {

        var xmlHttp = null;


        if (window.XMLHttpRequest) {

            xmlHttp = new XMLHttpRequest();


        else if (window.ActiveXObject) {

            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");



        return xmlHttp;



    // sends data to a php file, via POST

    function ajaxrequest(php_file, tagID) {

        var request = get_XmlHttp();

        // calls the function for the XMLHttpRequest instance


        var nume = document.getElementById('nume').value;

        var mesaj = document.getElementById('mesaj').value;


        // create pairs index=value with data that must be sent to server

        var the_data = 'nume=' + nume + '&mesaj=' + mesaj;


        request.open("POST", php_file, true);


        // adds a header to tell the PHP script to recognize the data as is sent via POST

        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        request.send(the_data);          // sends the request


        // will be transferred to the HTML tag with tagID

        request.onreadystatechange = function () {

            if (request.readyState == 4) {

                document.getElementById(tagID).innerHTML = request.responseText;






<body bgcolor="#DFFBFF">


<div id="resp">Here will be displayed the server response.</div><br />

<form action="codel.php" method="post" name="form1" onsubmit="ajaxrequest('codel.php', 'resp'); return false;">

  Your name: <input type="text" name="nume" id="nume" size="20" maxlength="33" /><br>

  Your message:<br>

  <textarea name="mesaj" id="mesaj" cols="25" rows="4"></textarea><br>

  <input type="submit" value="Send" />





  • The PHP script first ensures that all the data has been received, then gets that data using the strip_tag() function to delete possible HTML tags.

  • Responds with a Welcome message added to the textarea (with name="mesaj"), otherwise, a message to "fill in field tag".

Create an HTML file on the server (for example, named "forum.html or php") in the same directory where the file "codel.php" is, and add the following code to it:


// if data are received via POST

if (isset($_POST['nume']) && isset($_POST['mesaj']))


 // get data into variables, deleting the html tags

  $nume = strip_tags($_POST['nume']);

  $mesaj = strip_tags($_POST['mesaj']);

  // if the form fields are completed

  if (strlen($nume)>0 && strlen($mesaj)>0)


    echo 'Welcome <b>'. $nume. '</b><br />The message you've sent:<pre>'. $mesaj. '</pre>';




     echo 'Fill in all form fields';




  • When the user clicks the "Send" button, the instruction:
    onsubmit="ajaxrequest('codel.php', 'resp'); return false;"
    calls the Ajax function. The first parameter of the "ajaxrequest()" is the name of the PHP file and the second is the id of the tag where the response will be displayed. The "return false;" instruction stops the form to submit data by itself, and no page will be opened.

  • The "Request" function is used to request data in the form body, such as using: "document.getElementById(fieldID). value", and add the value to the "the_data" variable.

  • The open() contains the sending method (POST), the name of the PHP file (received as a parameter) and true to handle the request asynchronously ( request.open("POST", php_file, true); ).

  • The setRequestHeader() method is added to the request, to indicate that we sent the data as content of a Form (with POST).

  • After the request is sent with data we want to transmit to PHP ( request.send(the_data); ), when the response is completely received (request.readyState==4), it displays it with the following instruction, in the HTML tag with the id indicated in "tagID" parameter:
    document.getElementById(tagID).innerHTML = request.responseText;

  • When you open the "forum.php" file from the server it will display the following result. Test it yourself.



You can store this data in a database or perform other operations as you need, on the server side with the PHP script.