How to call a PHP function in JavaScript? How to call a PHP function in JavaScript? php php

How to call a PHP function in JavaScript?


You need to use ajax. There is a basic example:

myscripts.js

function AjaxCaller(){    var xmlhttp=false;    try{        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");    }catch(e){        try{            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        }catch(E){            xmlhttp = false;        }    }    if(!xmlhttp && typeof XMLHttpRequest!='undefined'){        xmlhttp = new XMLHttpRequest();    }    return xmlhttp;}function callPage(url, div){    ajax=AjaxCaller();     ajax.open("GET", url, true);     ajax.onreadystatechange=function(){        if(ajax.readyState==4){            if(ajax.status==200){                div.innerHTML = ajax.responseText;            }        }    }    ajax.send(null);}function check_year_event(year_id, event_id) { var year = document.getElementById(year_id).value; var event = document.getElementById(event_id).value;    callPage('file.php?year='+year+'&'+'event=+'+event,document.getElementById(targetId));}

file.php

<?php      function checkYearandEvent($year, $event) {      $year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")      if (mysql_num_rows($year_event) > 0) {       // do this      }     }    echo checkYearandEvent($_GET['year'], $_GET['event']);?>


You won't be able to do this in the way you might be expeting to. PHP is executed on the server, before the browser receives the HTML. On the other hand, JavaScript runs in the browser and has no knowledge of the PHP (or any other server side language) used to create the HTML.

To "call" a php function, you have to issue a request back to the server (often referred to as AJAX). For example, you could have a checkYear.php script which checks the event and returns some HTML indicating whether the check succeeded. When the HTML fragment gets back to the JavaScript, you inject it into the page.

Hope this helps!


JavaScript is a client side language, PHP is a server side language. Therefore you can't call PHP functions directly from JavaScript code. However, what you can do is post an AJAX request (it calls a PHP file behind the scenes) and use that to run your PHP code and return any data you require back to the JavaScript.