Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

something like this:

<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php 
query("hello");       ?>";    
}
</script>

<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.

share|improve this question
2  
simply no, there is no way to do this, except calling the required method using ajax. – TheVillageIdiot Aug 23 '11 at 17:58
5  
You know: PHP runs on the server, but JS on the client? This cannot work this way. – KingCrunch Aug 23 '11 at 17:58
wait wait, isn't <?php query("hello"); ?> rendered by php when page is loaded? if yes then he can get output of query("hello") in js function. – TheVillageIdiot Aug 23 '11 at 18:00
I know the code above is wrong, but I just used it to show what I want – JR93 Aug 23 '11 at 18:00
possible duplicate of Javascript and PHP functions – Mark Biek Aug 23 '11 at 18:01
show 2 more comments

5 Answers

up vote 9 down vote accepted

This is, in essence, what AJAX is for. Your page loads, then javascript uses the XMLHttpRequest object to send a request to a server. After the server responds (presumably with output), a javascript event gives you a place to work with the output, including simply sticking it into the page like any other piece of HTML.

Here's a really basic request script to accomplish what you discuss in your example code:

The javascript

function getRequest() {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    return req;
}

function getOutput() {
  var ajax = getRequest();
  ajax.onreadystatechange = function(){
      if(ajax.readyState == 4){
          document.getElementById('output').innerHTML = ajax.responseText;
      }
  }
  ajax.open("GET", "do_query.php", true);
  ajax.send(null);
}

The HTML

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

The PHP

// file do_query.php
<?php
  echo query('hello!');
?>

For further reading, check out the two documents I linked to above, and check out these tutorials: http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php

share|improve this answer

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.

share|improve this answer

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()) {
    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.

share|improve this answer

I believe that you should use a form or some sort of submit action in order to do that, keep in mind that doing so WILL transfer the user to another page, unless you are trying to do it via AJAX.

share|improve this answer
I want a way of doing it without reloading the page...prefferably – JR93 Aug 23 '11 at 17:59

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jqueryphp

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/"]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.