Ajax Course

Generally, we use data added in form fields to send it to a script on the server, specified in the "action" attribute of the <form> tag.
With Ajax, the data of the forms can be sent with both the GET and POST methods. However, considering that with GET the content that can be sent is limited and forms can have a large amounts of data, especially if you use a <textarea> 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. You can get the data from form fields using one of the following sintaxes:

1. Ussing the value of name attributes.
var get_data = document.formName.fieldName.value;
- formName is the value added in the name attribute of the <form> tag
- fieldName is the value added in the name attribute of the field

2. Using the ID attribute.
var get_data = document.getElementById(fieldID).value;
- fieldID is the value of ID attribute added in that field.

Here's a simple example to understand how an Ajax script can get data from a form, sends it to a php script and displays the response received.
  1) Create on the server a PHP file, named "test_form.php", and add into it the following code:
<?php
// 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>';
  }
  else {
    echo 'Fill in all form fields';
  }
}
?> 
- This PHP script check if data is received via POST, get that data, using strip_tag() function to delete posible html tags.
- If every field contains at least one character, return a Welcome message and the text added in the textarea (with name="mesaj"), otherwise, a message to "fill all form fields".

  2) Create an HTML file on the server (for example, named "ajax_form.html") in the same directory where the file "test_form.php" is, and add the following code into it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax and Form</title>

<script type="text/javascript"><!--
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
  var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');  // XMLHttpRequest object

  // gets data from form fields, using their ID
  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);      // sets the request

  // 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

  // Check request status
  // If the response is received completely, will be transferred to the HTML tag with tagID
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      document.getElementById(tagID).innerHTML = request.responseText;
    }
  }
}
--></script>
</head>
<body>

<div id="resp">Here will be displayed the server response.</div><br />
<form action="test_form.php" method="post" name="form1" onsubmit="ajaxrequest('test_form.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" />
</form>

</body>
</html>
- When the user click on the "Send" button, the instruction: onsubmit="ajaxrequest('test_form.php', 'resp'); return false;" calls the Ajax function. 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 ajaxrequest() function gets data of each form field, using: document.getElementById(fieldID).value, and add them in the "the_data" variable, as pairs (index=value), separated by '&' character.
- The open() contain the sending method (POST), the name of the php file (received as 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 send data as a 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 document.getElementById(tagID).innerHTML = request.responseText; instruction, in the HTML tag with the id indicated in "tagID" parameter.
- When you open the "ajax_form.html" file from the server, will display the falowing result. Test it yourself.
Here will be displayed the server response.

Your name:
Your message:


You can store these data in a database ore make any other operations you need, on the server side with the PHP script.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
AJAX and Forms

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (137624)
  2. PHP Unzipper - Extract Zip, Rar Archives (31752)
  3. Get Lower, Higher, and Closest Number (5332)
  4. Node.js Move and Copy file (28274)
  5. Node.js Move and Copy Directory (19979)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (313)
  2. Read Excel file data in PHP - PhpExcelReader (113)
  3. The Four Agreements (94)
  4. PHP Unzipper - Extract Zip, Rar Archives (91)
  5. The Mastery of Love (84)