Ajax is more than using the XMLHttpRequest object, consists in using, in addition to JavaScript, a server side language too.
In a URL can be included values to be transferred to a PHP file. These values are added in the URL after the page name and the '?', in a pair mode "index=value" (separated by the & character, if there are several such pairs).
<?php // if data are received via GET, with index of 'test' if (isset($_GET['test'])) { $str = $_GET['test']; // get data echo "The string '<i>".$str."</i>' contains ". strlen($str). ' characters and '. str_word_count($str, 0). ' words.'; } ?>2) Create an HTML file on the server (for example, named "ajax_get.html") in the same directory where the file "test_get.php" is, and add the following code in 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 GET</title> <script type="text/javascript"><!-- // sends data to a php file, via GET, and displays the received answer function ajaxrequest(serverPage, 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 (a pair index=value) var url = serverPage+'?test='+document.getElementById('txt1').innerHTML; request.open("GET", url, true); // define the request request.send(null); // sends data // 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> <h5 style="cursor:pointer;" onclick="ajaxrequest('test_get.php', 'context')"><u>Click</u></h5> <div id="txt1">A string that will be sent with Ajax to the server and processed with PHP</div> <div id="context">Here will be displayed the response from the php script.</div> </body> </html>- The "test_get.php" file contains a relatively simple PHP script. If it receives data via GET, with index of 'test', takes its value in the $str variable and, with "echo" returns a string that contains the received text and the number of characters and words in that text.
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net