Simple Ajax Example

Here is a simple Ajax example to grab a value from a PHP file. The same method would be used for a .txt file or a json request value.

JavaScript Code:

function get_txt(){
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var returnval=xmlhttp.responseText;
alert(returnval);
    }
  }
xmlhttp.open("GET","phpscript.php",true);
xmlhttp.send();
}

PHP Code:

<?php

echo "This text came from a PHP file!";

?>

To test, simply save the JavaScript code in an HTML file in the header and save the PHP code in a PHP file named phpscript.php. Then add the following button in the body of the HTML file:

<input type="button" value="TEST" onclick="get_txt()" />

Leave a Reply

Your email address will not be published. Required fields are marked *