Ajax Course

With Ajax you can send data to a PHP script via GET and POST in the same request. The process is similar to sending data through the POST, it's actually the same, being only applied a "trick".
Data added in the URL address (the index=value pairs) are recognized by the server as being sent via GET. Thus, to send data using GET and POST in the same time, proceed as follows:
        - the values that we want to send with GET are added in the URL address that is set in the "open()" method
        - the values to be sent with POST method are added in the parameter of the "send()" function.


• To understand how to send data with AJAX using GET and POST togeter, in the same request, apply and study the following example:
  1) Create on the server a PHP file, named "get_post.php", and add into it the following code:
<?php
// if data are received via GET, with index='timp' and via POST, with index='nume', and has at least one character
if (isset($_GET['timp']) && isset($_POST['nume']) && strlen(trim($_POST['nume']))>0) {
  // gets data
  $nume = $_POST['nume'];
  $timp = $_GET['timp'];

  // return the response
  echo 'Hy <b>'.$nume.'</b>.<br />You send data to the server after you`ve spent <i>'. $timp. '</i> seconds on this web page.';
}
else {
  echo 'Add your name.';
}
?>
- This PHP script checks if data is received via GET, with index of 'timp' and via POST with index of 'nume'. Gets that data and include it in the message that is returned by "echo".
- strlen(trim($_POST['nume']))>0 checks if the value of $_POST['nume'] it has at least one character that is not a space.

  2) Create a HTML file on the server (for example, named "get_post.html") in the same directory where the file "get_post.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="ro">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Ajax example GET and POST</title>

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

  // create the URL with data that will be sent to the server, via GET (a pair index=value)
  var  url = php_file+ '?timp='+document.getElementById('timp').innerHTML;

  // create pairs index=value with data that must be sent to server, via POST
  var  d_post = 'nume='+document.getElementById('nume').value;

  request.open("POST", url, 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(d_post);        // 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;
    }
  }
}

// gets and displays in a html tag (with id="timp") the number of second the user spend on the page
var secunde = 0;
function getSeconds() {
  secunde++;    // add one unit

  // add the valur in the html tag that has id="timp"
  document.getElementById('timp').innerHTML = secunde;
}
setInterval("getSeconds()", 1000)    // calls the function at every second
--></script>
</head>
<body>

<div id="sec"><span id="timp"> </span> seconds</div>
<form action="get_post.php" method="post" name="form2" onsubmit="ajaxrequest('get_post.php', 'resp'); return false;">
  Your name: <input type="text" name="nume" id="nume" size="20" maxlength="33" />
  <input type="submit" value="Send" />
</form>
<div id="resp"> </div>

</body>
</html>
- As you can see, besides the function for Ajax, ajaxrequest(), there is another function, named "getSeconds()". At every call, this function increment a variable by one unit (second) and displays it in a HTML tag that has id="time", and this function is called every second by "setInterval()".
- When the user click on the "Send" button, it calls the "ajaxrequest()" function. After it is created the instance of the XMLHttpRequest object, gets the data to be sent via GET (the number of seconds recorded in the tag with id="timp") and add it in the URL address.
- The data that must be sent via POST are defined in the d_post variable, which will be the parameter of "send()" method.
- More necessary explanations can be found in the script code.

This example will display the fallowing result. To test it, add a name in the text-box and click on the "Send" button.
seconds
Your name:  

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Sending data with GET and POST in the same request

Last accessed pages

  1. Select in MySQL, Output results in HTML Table (19495)
  2. The Mastery of Love (7438)
  3. CSS cursor property - Custom Cursors (6091)
  4. Disable button and Enable it after specified time (17531)
  5. PHP Unzipper - Extract Zip, Rar Archives (32244)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (472)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)