Call php function from javascript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts:186

Call php function from javascript

Is it posible to run a php function through a javascript function?
Something like this:

Code: Select all

<div id="php_code">Here will be added the Php Code via jsFun()</div>
<span onclick="jsFun();">Test</span>
<script>
function jsFun() {
  document.getElementById('php_code').innerHTML = '<?php phpFun("hello"); ?>';
}
</script>
I basically want to run the php function phpFun(), when I click on the <span> "Test" that calls the jsFun() function.
- How can I call a php function from javascript?

Admin Posts:805
PHP is evaluated at the server; javascript is evaluated at the client-side/browser, thus you can't call a PHP function from javascript directly. But you can use Ajax to access a php file from javascript, through a HTTP request (GET, POST), and get the php response in javascript.
Example.
- HTML-JavaScript code:

Code: Select all

<div id="php_code">Here will be added the Php response via jsFun()</div>
<span onclick="jsFun();">Test</span>
<script>
function jsFun() {
  var request =  (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');  // XMLHttpRequest instance

  // create pairs index=value with data that must be sent to php
  var  datas = 'do=phpFun';

  request.open("POST", 'file.php', true);    // set the request

  // adds  a header to tell the PHP script to recognize the data as is sent via POST
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(datas);		// sends datas to php

  // Check request status
  // If the response is received completely, adds the response in #php_code
  request.onreadystatechange = function() {
    if(request.readyState == 4) {
      document.getElementById('php_code').innerHTML = request.responseText;
    }
  }
}
</script>
- PHP code (in file.php):

Code: Select all

<?php
function phpFun() {
    return 'Hello';
}

if (isset($_POST['do']) && $_POST['do'] == 'phpFun') {
  echo phpFun();
} 
For more details about Ajax and PHP, see the lessons from https://coursesweb.net/ajax/.

Similar Topics