Wywołaj funkcję php z JavaScript

80

Czy istnieje sposób, w jaki mogę uruchomić funkcję php za pomocą funkcji JS?

coś takiego:

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

Zasadniczo chcę uruchomić funkcję php query("hello"), kiedy klikam href o nazwie „Test”, który wywoła funkcję php.

Jason Russell
źródło
4
po prostu nie, nie ma sposobu, aby to zrobić, z wyjątkiem wywołania wymaganej metody przy użyciu ajax.
TheVillageIdiot
9
Wiesz: PHP działa na serwerze, ale JS na kliencie? To nie może działać w ten sposób.
KingCrunch
czekaj czekaj, czy nie jest <?php query("hello"); ?>renderowane przez php po załadowaniu strony? jeśli tak, to może uzyskać wynik query("hello")w funkcji js.
TheVillageIdiot
Wiem, że powyższy kod jest nieprawidłowy, ale właśnie użyłem go, aby pokazać, czego chcę
Jason Russell
1
możliwy duplikat funkcji Javascript i PHP
Mark Biek

Odpowiedzi:

144

To jest w istocie, co AJAX jest za . Twoja strona ładuje się i dodajesz zdarzenie do elementu. Kiedy użytkownik wywołuje zdarzenie, powiedzmy, klikając coś, Twój JavaScript używa obiektu XMLHttpRequest do wysłania żądania do serwera.

Gdy serwer odpowie (prawdopodobnie z wyjściem), inna funkcja / zdarzenie Javascript daje ci miejsce do pracy z tym wyjściem, w tym po prostu umieszczając go na stronie, jak każdy inny element HTML.

Możesz to zrobić „ręcznie” za pomocą zwykłego JavaScript lub możesz użyć jQuery. W zależności od wielkości projektu i konkretnej sytuacji, prostsze może być użycie zwykłego JavaScript.

Zwykły JavaScript

W tym bardzo podstawowym przykładzie wysyłamy żądanie, myAjax.phpgdy użytkownik kliknie łącze. Serwer wygeneruje treść, w tym przypadku „hello world!”. Umieścimy w elemencie HTML z id output.

Plik javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      '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;
    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;
            }
        }
    }
    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);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

The HTML

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

The PHP

// file myAjax.php
<?php
  echo 'hello world!';
?>

Try it out: http://jsfiddle.net/GRMule/m8CTk/


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() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/

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.

Documentation

Chris Baker
źródło
3
-1, half an answer, OP asked how to call a php function from javascript. Pou only showed how to call a php PAGE. You need to add post variables in the ajax call and php checking for those post variables and then calling that php function if those post variables exist.
M H
6
@Hanoncs With nearly infinite possible arrangements of server-side code, it is not constructive or even possible for me to guess what architecture the OP is using. It is not germane to the immediate problem statement, either, since the OP does not reference POST (or GET) or the need to pass values. I think your downvote is misplaced, and I'll not be adding to my answer arbitrary speculation about a subject not contained in the OP. Thanks for the feedback though.
Chris Baker
When I use your code, I get an error because of the use of "var" in front of the function declaration. Removing "var" and it works.
Jayden Lawson
16

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.

Dor
źródło
3
@Hanoncs: This is the answer. OP asked whether you can execute a PHP function via JS. The answer is - you can't. If he would have asked whether you can issue an HTTP request that will make the web server to activate a PHP script which will run a PHP function - then yes - that is possible. But he didn't ask for this, ergo I don't write irrelevant data.
Dor
8
Haha come on man, you know that's what the OP meant by his question. if he knew how to explain it exactly like that he would already know how to do it.
M H
11

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.

morsik
źródło
3

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

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/"]
Xaxis
źródło
4
Aside from the obvious bias people have in regard to calling PHP functions via JavaScript, explain to me exactly why my answer has been down voted as much as it has? I'm legitimately answering the question at hand with a solution, am I not?
Xaxis