Javascript and PHP functions

You can not call a PHP function from Javascript…

Javascript is a client language (it’s executed on the Web browser, after receiving the web page) while PHP is on the server side (it’s executed before the web page is rendered). You have no way to make one call another.

…but you can get the result of an external PHP script

There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.

This process is what we call AJAX, and it’s far easier to do it with a good tool than yourself. Have a look to JQuery, it’s powerful yet easy to use Javascript library that has built-in AJAX helpers.

An example with JQuery (client side) :

$.ajax({
   type: "POST", // the request type. You most likely going to use POST
   url: "your_php_script.php", // the script path on the server side
   data: "name=John&location=Boston", // here you put you http param you want to be able to retrieve in $_POST 
   success: function(msg) {
     alert( "Data Saved: " + msg ); // what you do once the request is completed
   }

Leave a Comment