PHP and AJAX Demo

Click the button Show My IP address to see what your IP addresss is. With the use of AJAX, notice that there is no page refresh when you hit the button and you are presented with your IP address.



How HTML, PHP, AJAX Made It Happen?

The Javascript:

<script type="text/javascript"> function show_my_ip_address() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) { document.getElementById('my_ip').innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","get_ip.php",true); xmlhttp.send(null); } </script>

PHP script:

<?php echo 'Your IP address is <h1>'.$_SERVER['REMOTE_ADDR'].'</h1>'; ?>

The HTML:

<input type="button" name="view_ip" value="Show My IP address" onclick="show_my_ip_address()" /> <br /> <div id="my_ip" style='height:70px;width:400px;overflow:hidden;'></div>

Behind the scene:

The javascript function show_my_ip_address() first creates a XMLHttpRequest object. This object is primary object we need to communicate with the server-end script (php). We send the request, call the php code through:

xmlhttp.open("GET","get_ip.php",true); xmlhttp.send(null); And we know when the server has responded to our request through: xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) { document.getElementById('my_ip').innerHTML = xmlhttp.responseText; } } Here, the response of the server script (get_ip.php) is contained by xmlhttp.responseText. We set its data to the html elemenet, 'my_ip'

If you look at our HTML source, the javascript function is invoked when the user clicks on the button.

While the PHP script (get_ip.php) simply echoes a string showing the IP address of the user through the user of $_SERVER['REMOTE_ADDR']

Sponsor

stats

Hosted by T35 Free Web Hosting. Womens Sunglasses - Online Casino - Drug Rehab - Best Online Colleges - Web Hosting - Prada Sneakers - SEO Services