How to execute PHP code from JavaScript

Monday, November 14th, 2011|Beginner tips, Brainstorming, Verison 4.2|by Romans

If you are only starting with PHP and Web Development, questions like “how to execute PHP from JavaScript” are inevitable. First I must say that JavaScript and PHP are living on the different sides of the fence and are simply throwing ball over to each-other. So your JavaScript needs a request to the PHP asking it to execute some code.

Unless you want to reinvent the wheel, you should look into using some AJAX / PHP library. Agile Toolkit amongst other can be a great help when you want to build interaction between JavaScript and PHP.

JavaScript event to trigger PHP function

Before going into AJAX, here is how you could produce random numbers in plain JavaScript:

<button id=”mybutton”>Click Me</button>
<script>
$(‘#mybutton’).click( function(){
$(‘#mybutton’).text( Math.random() );
}
</script>

Agile Toolkit comes up with an elegant way in PHP:

$mybutton=$this->add(‘Button’)->setLabel(‘Click me’);
if($mybutton->isClicked()){
$mybutton->js()->text( rand() )->execute();
}

See this example in action

More information of Binding JavaScript actions to PHP

Code achieves same result, but the “Rand” value is calculated on the server. This code relies on the JavaScript function “ajaxec()” defined in JavaScript Utility library (Universal Chain).

How to make it even better?

Wouldn’t it be even greater if you could bind any action to any object like that?

$this->add(‘H3′)->set(‘Move mouse over’)->on(‘mouseover’, function(){

$this->js()->text(‘Thank you’)->execute();

});

Write a comment