Server Side Versus Client Side Scripting
Server Side Versus Client Side Scripting
|
As already explained, PHP code is processed at the Web server before anything is returned to the browser. This is referred to as server-side processing. Most Web programming works this way: PHP, ASP, Perl, C, and others.
However, a few languages are processed by the browser after it receives the page. This is called client-side processing. The most common example of this is JavaScript.
NOTE : Despite the similarity in their names, Java and JavaScript are far from being the same.
Many Web developers are familiar with JavaScript, but this does not make them Java
programmers. It’s important to remember that these languages are not the same.
This can lead to an interesting problem with logic. The following example
demonstrates what I mean:
<script language=”JavaScript”>
if (testCondition())
{
<?php
echo “<b>The condition was true!</b>”;
?>
} else {
<?php
echo “<b>The condition was not true.</b>”;
?>
}
</script>
The resulting code from the previous snippet follows; notice that the
JavaScript has been left intact and untouched, but the PHP code has been
evaluated. PHP ignores the JavaScript code completely:
<script language=”JavaScript”>
if (testCondition())
{
<b>The condition was true!</b>
} else {
<b>The condition was not true.</b>
}
</script>
As you can see, this code will cause JavaScript errors when executed. Be
cautious when combining PHP and JavaScript code: It can be done, but it
must be done with attention to the fact that the PHP will always be evaluated
without regard for the JavaScript. To successfully combine the two, it’s
generally necessary to output JavaScript code with PHP.
The following example does just that:
<script language=”JavaScript”>
if (testCondition())
{
<?php
echo “document.write(‘<b>The condition was true!</b>’);”;
?>
} else {
<?php
echo “document.write(‘<b>The condition was not true.</b>’);”;
?>
}
</script>
As you can see, doing this gets complicated very quickly, so it’s best to avoid
combining PHP and JavaScript. However, the resulting code below shows
you that this will work.
<script language=”JavaScript”>
if (testCondition())
{
document.write(‘<b>The condition was true!</b>’);
} else {
document.write(‘<b>The condition was not true.</b>’);
}
</script>
No comments:
Post a Comment