How to call a php function using JavaScript (AJAX)

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to call a php function using JavaScript (AJAX)

Post by Neo » Sun Feb 07, 2010 4:16 pm

Without the refreshing page, this script will call the php file YourFile.php and the output will come as text. You need to include the file where php function exists to YourFile.php and call that function from YourFile.php.

Code: Select all

<html>
<body>

<span id="header"></span>

<script type="text/javascript">
xmlhttp=null;
if (window.XMLHttpRequest){
        // code for Firefox, Mozilla, IE7, etc.
        xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject){
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

if (xmlhttp!=null){
        xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4){
                        x=xmlhttp.responseText;
                        document.getElementById("header").innerHTML=x;
                }
        }

        xmlhttp.open("GET", "YourFile.php", true);
        xmlhttp.send(null);
}
else{
        alert("Your browser does not support XMLHTTP.");
}
</script>
</body>
</html>
Post Reply

Return to “PHP & MySQL”