Using PHP and Javascript together

Javascript and PHP Discussion document

One of the big problems that new users to PHP have is understanding where Javascript stops and PHP starts. This article addresses those fundamentals.


Javascript works only on the browser. That’s the software you use on your computer to view web pages. How those pages will look may differ depending on the browser that you use and each browser may have different standards for Javascript.

Benefits of Javascript:

  1. Quick validation of information
  2. Incredible control over the presentation of a page

There are 3 major reasons for not using Javascript exclusively:

  1. Inconsistent Browser support
  2. No ability to access a database
  3. Business rules are visible

Now, you may consider that your “Business Rules” are unimportant, and this may be true, but a great many sites process information in a way that they don’t want “hacked”. One of my sites, for instance, generates keycodes when a user purchases or registers software. You don’t want anyone to be able to see the methodology of producing those keycodes.


PHP works only on the webserver.

It is oblivious to the browser being used. PHP may process and generate nothing or it may generate a text stream. Depending on the “headers” being sent at the beginning of the text stream the text will be interpreted as HTML, XML or even grapics files. PHP scripts will only be activated when a request is made to the webserver and will cause a page to refresh.

Benefits of PHP:

  1. Access to databases
  2. Business rules are hidden.
  3. Only the result of the PHP script is sent to the browser so quicker to load

There is 1 major reason not to use PHP exclusively:

* Users don’t like to have the page being submitted and refreshed constantly especially for pages where there is scrolling. Javascript can eliminate the need to submit for basic alphanumeric validation.

Example 1: PHP creates Javascript Variables

I have a tutorial on iFrames on this site. See muck/example.php. In this the user selects an animal and javascript causes a form on an iFrame to be submitted. This then returns with a javascript array and the values are fed back into a form on the parent page.

So, what is the code on the iFrame? The file is called noises.php and looks like this when I select lion:[html]

Hidden Frame

Iframe should have width=”0″ height=”0″!

Iframe would normally have the bare minimum of html, this needs to be fast, not pretty.

Yet the original, serverside script is much longer:

Hidden Frame

Iframe should have width=”0″ height=”0″!

Iframe would normally have the bare minimum of html, this needs to be fast, not pretty.


Want to know more – check my other Javascript, AJAX or PHP articles


Recent Comments


Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.