Is there a way I can run a php function through a JS function?

something like this:

<script type="text/javascript">
function test(){
query("hello");       ?>";    

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"     
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>

I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.

Solution 1

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query
function getOutput() {
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  return false;
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
    }"GET", url, true);
    return req;


<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>


// file myAjax.php
  echo 'hello world!';

Try it out:

With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
      complete: function (response) {
      error: function () {
          $('#output').html('Bummer: there was an error!');
  return false;

Try it out:

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.


Solution 2

PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.

Solution 3

The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:

function someFunction() {
    echo 'Answer';

if ($_GET['do'] === "someFunction") {

and then, catch the answer with JS (i'm using jQuery for making AJAX requests)

Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.

Solution 4

I recently published a jQuery plugin which allows you to make PHP function calls in various ways:

Simple example usage:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Solution 5

I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:


echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";

function myPhp(){
echo"The page says: Hello world!<br>";

echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";

<div id="mainx"></div>

function callPhp(){
var tagDiv1 = document.createElement("div"); = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";

<input type="button" value="CallPHP" onclick="callPhp()">

Note: The texto.txt file has the content 'Hello world! (Old content).

The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.

But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.

So, If you don't want the user to know what commands are running on the server:

  • You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).


  • If the output of commands on the server-side is not delayed:
    • You 'can' use the execution of the commands directly from the page (less 'cognitive' resourcesless PHP and more Bashand less code, less time, usually easier, and more comfortable if you know the bash language).
  • Otherwise:
    • You 'must' use Ajax.