Pages

Wednesday 20 November 2013

How to call PHP function from JavaScript function? Always use AJAX.

How to call PHP function from JavaScript function? Always use AJAX.

Recently, I was developing a web application in PHP. I get into the need of calling my PHP function from my Javascript function. This is the common thing when you are developing a web application in PHP and have to call a PHP code from Javascript to refresh only a certain portion of your web page with server results. Always use AJAX to achieve this functionality. Using AJAX you can call server side code / functions (your PHP code) from client side (Javascript). Below is the PHP and Javascript code snippet to illustrate this concept. 

This is very simple example on how to call server side functions of PHP from client browsers (Javascript)? In following example, I have a PHP file named myscript.php which has function named myfunction(). This function uses two $_POST variables and just echoes them. I have mydiv HTML div anywhere on my webpage which I want to refresh with the result which is returned from my PHP script. In my Javascript code, I am using AJAX to call my PHP script with parameters and POST method. The result which is getting returned, I am showing that in mydiv HTML div. 

Have a look at this very simple PHP AJAX example:

PHP code

<?php

myfunction();

function myfunction()
{
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
?>

HTML code

<div id="mydiv"></div>

Javascript code

var data =" hello world";
var data2=" hello all";
function run()
{
$.ajax(
{
                   url: 'myscript.php',
                data: {'q': data,'z':data2},
                   type: 'post',
                   success: function(output) 
                {
                          //alert(output);
                          document.getElementById("mydiv").innerHTML += output; //add output to div  
                }
}
          );
}

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.