Run a PHP function with Javascript

Asked

Viewed 1,122 times

1

I need to call a PHP function through Javascript by clicking on an element (event onclick).

I made these basic lines to see if anyone can help.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
</head>
<body>

    <button type="button" onclick="funcaoJava()">Enviar</button>

<?php
    funcaoPHP () {
        echo "PHP EXECUTADO":
    }
?>

    <script>
        function funcaoJava(){
            // Chamar a função PHP
        }
    </script>
</body>
</html>
  • 1

    JS has no connection to PHP, except for Ajax.

  • Got it. So there’s no possibility of doing this without using ajax?

  • There is no way because PHP runs on the server and JS in the browser.

  • 1

    It’s a sin to name a function with funcaoJava in Javascript!

1 answer

4

"- call a function in PHP via Javascript"

You can’t do that! PHP is a language that runs on the server (back-end) while (in your case) Javascript runs on the client (front-end).

There are ways Javascript can "communicate" with PHP. I’ll illustrate!

But, first of all, you need to ask yourself: the PHP function will be called already in the page rendering and does not rely on post-rendering data?


If yes, then you can directly render:

(what I find bad practice, unnecessary, gambiarra, etc)

<?php
    function minhaFuncaoPHP($param1, $param2){
        return ($param1+$param2);
    }

    $arg1 = 10;
    $arg2 = 7;
?>

<button type="button" onclick="funcaoJava()">Enviar</button>

<script>
    function funcaoJava(){
        let retornoPHP = '<?php echo minhaFuncaoPHP($arg1, $arg2); ?>';
        alert(retornoPHP);
    }
</script>

If not, you will have to create a page that receives a Javascript request. This way, you can transmit data to PHP and return this data to Javascript.

This PHP page is called Webservice (does not have to be in PHP) and this practice is popularly known as "consume a webservice". As it comes to Javascript, we say "consume a webservice with AJAX".

Webservice

(Source: W3schools - AJAX Introduction)

Take this simple example:

1) Webservice in PHP: funcao.php

<?php

function minhaFuncaoPHP($param1, $param2){
    return ($param1+$param2);
}

$dados = json_decode(file_get_contents('php://input'), true);

$resposta = minhaFuncaoPHP($dados['campo1'], $dados['campo2']);

echo json_encode($resposta);

Note that this page simply: 1) loads the function; 2) "parsea" the data received via AJAX; 3) calls the function that handles the data; 4) "shows" this data in JSON format.

2) Client in HTML/Javascript:

<div>
    <label>
        Campo 1
        <input type="number" name="campo1">
    </label>
    <label>
        Campo 2
        <input type="number" name="campo2">
    </label>
</div>
<div>
    <button type="button">Enviar</button>
</div>
<script>
    let btn = document.querySelector('button[type=button]');
    btn.addEventListener(
        'click',
        function(){
            let data = {
                campo1: document.querySelector('input[name=campo1]').value,
                campo2: document.querySelector('input[name=campo2]').value
            }

            let ajax = new XMLHttpRequest();

            ajax.open('post', 'funcao.php');

            ajax.onreadystatechange = function(){
                if (
                    ajax.readyState == 4
                    && ajax.status >= 200
                    && ajax.status <= 400
                ) {
                    let respostaAjax = JSON.parse(ajax.responseText);

                    // Aqui os dados já foram tratados.
                    // Faça o que quiser com eles:
                    console.log(respostaAjax);
                }
            }

            ajax.send(JSON.stringify(data));
        },
        false
    );
</script>

Just understand this: this is a minimal example! Don’t get tied to Ctrl+C / Ctrl+V. Consider reading some articles on the subject and delve into this very useful subject.

Recommended readings:

Wikipedia - Web service

W3schools - AJAX Introduction

Soen: Send JSON data to PHP using Xmlhttprequest w/o jQuery

PHP: php:// - Handbook

Soen: PHP "php://input" vs $_POST

Browser other questions tagged

You are not signed in. Login or sign up in order to post.