Oct
30
Posted on 30-10-2007
Filed Under (Tutorial) by chintan

Javascript can be used with PHP without problems, as long as you keep in mind that they operate in different environments (see Frames, JavaScript, and PHP Overview):

PHP, is server side. Therefore, if you want to pass data from a form to PHP, you have to submit it and load the page again. There is no getting about it.

Javascript is client side (run in the browser), and can help you with dynamic functionality. You can easily use JavaScript and PHP jointly. However, just like PHP knows nothing about Javascript. PHP will just echo the Javascript code to the HTML page, just as it would echo the value of a string variable.

EXAMPLE

<?php

echo ‘Welcome to PHP’;

?>

and

<?php

echo ‘<script type=”text/javascript”>

<!–

if ( 1 ) {

window.open(\’any.php?name=News\’, \’hello world\’,

\’HEIGHT=500, resizable=yes, WIDTH=500\’);

}

//–>

</script>’;

?>

They both echo strings, of which the first one is simply displayed in the client’s browser as a welcome message, while the second one is take by the client’s browser and leads to the browser sending a request for the News module, which in turn sends the usual home page of a PHP site to be displayed on the client.

With this in brain, Javascript does not demand any special treatment when used in PHP blocks. Just append the Javascript code to the $content variable of the block and you are done. Of course, you have to escape double quotes – and it is a good idea to add a newline (\n) to the end of each Javascript line (see Javascript and BLOCKs).

If you use sed, the following sequence of set commands, applied to a Javascript file, will produce the right PHP code to include in the PHP block:

(A) 1,$s/”/\\”/g

(B) 1,$s/^/\$content \.= “/

(C) 1,$s/$/”;/

(D) 1,$s/”;$/\\n”;/

A Escape all double quotes.

B. Add a newline \n at the end of each JS line

C Add the string ‘”;’ at the end of every line.

D. Add the string ‘$content .= “‘ at the start of every line

Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Live
  • StumbleUpon
  • Technorati
  • YahooMyWeb
(0) Comments    Read More   
Post a Comment

You must be logged in to post a comment.