Back Next

Ajax Tutorial

A simple calculator




The Frontend

This is pretty straightforward, some form fields and a submit button that calls a function.

  1. <input type="text" id="num1" size="8" />

  2. <input type="text" id="num2" size="8" />

  3. <select id="op">

  4. <option value="add">+</option>

  5. <option value="subtract">-</option>

  6. <option value="multiply">*</option>

  7. <option value="divide">/</option>

  8. </select>

  9. <input type="button value=" = " onClick="doMath();" />

  10. <div id="answer" />

The Backend

This is where most of the work gets done. The first three if statements do some basic error handling with the switch statement doing the actual math.

  1. <?

  2. if ($_GET['op']=="" || $_GET['num1']=="" || $_GET['num2']==""){ // what?

  3. echo "<span class=\"error\">Complete all fields</span>";

  4. exit;

  5. }

  6. if ($_GET['op']== "divide" && $_GET['num2']== "0"){ // what?

  7. echo "<span class=\"error\">Division by zero</span>";

  8. exit;

  9. }

  10. if(!is_numeric($_GET['num1'] || !is_numeric($_GET['num2'])){ // what?

  11. echo "<span class=\"error\">Invalid numbers</span>";

  12. exit;

  13. }

  14. switch($_GET['op']){ // what?

  15. case "add":

  16. echo $_GET['num1'] + $_GET['num2'];

  17. break;

  18. case "subtract":

  19. echo $_GET['num1'] - $_GET['num2'];

  20. break;

  21. case "subtract":

  22. echo $_GET['num1'] * $_GET['num2'];

  23. break;

  24. case "subtract":

  25. echo $_GET['num1'] / $_GET['num2'];

  26. break;

  27. }

  28. ?>

The Script

The AJAX script collects the values and sends it to the php script, which does the math. The AJAX then takes the answer and plugs it into the appropriate div.

  1. http = getHTTPObject(); // what?

  2. function getHTTPObject() {

  3. var xmlhttp;

  4. if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){

  5. try {

  6. xmlhttp = new XMLHttpRequest();

  7. }catch(e){

  8. xmlhttp = false;

  9. }

  10. }

  11. return xmlhttp;

  12. }

  13. function doMath(){

  14. var url = "backend.php?op=" + document.getElementById('op').value; // what?

  15. url += "&num1=" + document.getElementById('num1').value;

  16. url += "&num2=" + document.getElementById('num1').value;

  17. http.open("GET", url, true); // what?

  18. http.onreadystatechange = handleHttpResponse;

  19. http.send(null);

  20. }

  21. function handleHttpResponse(){ // what?

  22. if(http.readyState == 4){

  23. document.getElementById('answer').innerHTML = http.responseText;

  24. }

  25. }


Mar 21, 2010 Back40Design, Javelin

Back Next