How to call PHP function from within JavaScript

12.1k Views Asked by At

Here what I exactly need is, if I move over the HTML button, specific div tag should be reloaded without reloading whole page.

2

There are 2 best solutions below

2
On

PHP works on the server side, and JavaScript on the client side. So to do this, you would have to make a request to the server. If you want to use plain JavaScript, take a look at Ajax:

http://www.w3schools.com/ajax/

<script>
function myPhpFunctionCall()
{
  var xmlhttp;
  xmlhttp=new XMLHttpRequest();

  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      // Do something with the results here
    }
  }
  xmlhttp.open("GET","my_function.php",true);
  xmlhttp.send();
}
</script>

Or, if you want to use jQuery, you can use their get method:

<script>
    $.get('http://yourdomain/your_script.php');
</script>
0
On

Simple way to solve this any of your function in place of json_encode() :

$(document).ready(function() {

         var php_var = '<?php echo json_encode($form); ?>';          

});


$('#element').hover(function() {

         $('#form_container').html(php_var);
}, function() {

         $('#form_container').html('');
});