Developer's Guide :: Javascript Events

From Delphi for PHP Documentation Wiki

Jump to: navigation, search

VCL for PHP allows you to add JavaScript code in a very convenient way, using events, so all your JavaScript and PHP code are organized in the same way.

Here is an example of how you can request information from the user using JavaScript:

 
function Button1JSClick($sender, $params)
{
?>
  //Add your javascript code here
  return confirm("Press OK button")
<?php
}
 

You can generate such a routine from the IDE by switching to the Javascript Tab on the Object Inspector and double clicking on the OnClick event. This escapes from the PHP code to allow you write JavaScript code.


[edit] Javascript events vs PHP events

If you come from the desktop development world, it will sound strange to you that a button has two OnClick events. One in the Events Tab and another in the Javascript tab on the Object Inspector.

The reason of having two types of events is because, when developing web applications, you can get notified about the button clicked in two different places, the client (browser) and the server.

Let's see what happens when a user clicks a button on a browser: -If the button has a javascript OnClick event handler attached, that event will be executed -If you don't return false on that event, that instructs the browser to continue the sequence -The next step is to submit the current form (unless the button is of a different type than btSubmit) -Once the form is submitted, the PHP script is executed and the button checks if it has been pressed -If it has been pressed, then, if there is a PHP OnClick event attached, it executes it

So the question you have to ask yourself about whether to use a javascript or a PHP event is "when" and "where" do you want to execute your code, in the browser or in the server.


[edit] A nonsensical snippet to illustrate using a javascript function.

Create a new form and in the forms onshowheader event make it look like this:

 
               function Unit1ShowHeader($sender, $params)
               { //this will output a js function:
               ?>  
               <script>
               function buttonpressed(bp)
               {
               alert('You pressed '+bp+'.');
               }
               </script>
               <?php
 
               }
 

Drop a button on the form and make the javascript onClick event look like this:

 
               function Button1JSClick($sender, $params)
               {
 
               ?>
               buttonpressed(1);
               return false; //stops the button submit to the server.
               <?php
 
               }
 
Personal tools