ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

PHP On-The-Fly!

(Page 3 out of 4)

Let's try a more advanced example. In the following example, the visitor can enter two numbers, and they are added up by PHP (and not by JavaScript). This shows the true power of PHP and the XML HTTP Request Object.

This example uses the same script.js as in the first example, so you don't need to create this again. First, copy the code below and paste it in a file called 'server2.php':

// Get numbers
$num1 = intval($_GET['num1']);
$num2 = intval($_GET['num2']);

// Return answer
echo ($num1 + $num2);

?>

And then, copy the code below, and paste it in a file called 'client2.php'. Please note though that you need to edit the line that says 'http://www.yourdomain.com/server2.php' to the correct location of server2.php on your server.




</span>Example 2<span class="sc2"><span class="kw2">
src="script.js" type="text/javascript">

type="text/javascript">
        function calc() {
                num1 = document.getElementById ('num1').value;
                num2 = document.getElementById ('num2').value;

                var element = document.getElementById('answer');
                xmlhttp.open("GET", 'http://www.yourdomain.com/server2.php?num1=' + num1 + '&num2=' + num2);
                xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                element.value = xmlhttp.responseText;
                        }
                }
            xmlhttp.send(null);
        }


        Use the below form to add up two numbers. The answer is calculated by a PHP script, and not with JavaScript. What's the advantage to this? You can execute server-side scripts (PHP) without having to refresh the page.

        type="text" id="num1" size="3" /> + type="text" id="num2" size="3" /> = type="text" id="answer" size="5" />

        type="button" value="Calculate!" OnClick="calc();" />

When you run this example, you can add up two numbers, using PHP and no reloading at all! If you can't get this example to work, then have a look on http://phpit.net/demo/php%20on%20the%20fly/client3.php to see the example online.

« Previous: Example One
Next: Any Disadvantages...? »



Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction
  2. Example One
  3. Example Two
  4. Any Disadvantages...?
Bookmark Article
Download Article
PDF
Download this article as a PDF file