OSdata.com: holistic issues 

OSdata.com

example source code
simpleajax.php

    This article describes how to get simple AJAX up and running using PHP on the server side and JavaScript on the web browser side.

    There are three parts: (1) the originating PHP, (2) the JavaScript, and (3) the server PHP dispatch.

summary

    The goal is simple, at some point (whether by timer or user click or some other interaction) you want the web browser to go back to your server and pick up more information and insert that new information into the web page without reloading the entire web page.

    This interaction between server and browser is called AJAX (Asynchronous JavaScript And XML). In the more complicated version, your server will send XML or JSON data and your JavaScript will parse the incoming data and then build the web browser presentation.

    In this simple version, the server will send back formatted HTML, CSS, and JavaScript and the web browser JavaScript function will simply load it onto the web page “as is”.

    Once you have mastered this simple method, you can take on more ambitious projects.

the game

    Building a game — open source code This is the actual source code from a new web game. See the game at thissideofsanity.com and read how this was built starting at example code.

    This is example code from the SlamZee project and This Side of Sanity, released under Apache License 2.0.

    Copyright 2013 Milo (for software), Distribution and website handled by Strazbick.com

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    This narrative uses anchor links so that you can follow the building of this software in chronological order. Go to software explanation to start reading. Go to thissideofsanity.com to see the working software.

Google

example source code
simpleajax.php

    This is example code from the SlamZee project and This Side of Sanity, released under Apache License 2.0.

    There are three parts: (1) the originating PHP, (2) the JavaScript, and (3) the server PHP dispatch.

    I will carefully explain the code. Both files will be presented at the end of the discussion for easy copy and paste.

what you accomplish

    The goal is simple, at some point (whether by timer or user click or some other interaction) you want the web browser to go back to your server and pick up more information and insert that new information into the web page without reloading the entire web page.

    This interaction between server and browser is called AJAX (Asynchronous JavaScript And XML). In the more complicated version, your server will send XML or JSON data and your JavaScript will parse the incoming data and then build the web browser presentation.

    In this simple version, the server will send back formatted HTML, CSS, and JavaScript and the web browser JavaScript function will simply load it onto the web page “as is”.

    Once you have mastered this simple method, you can take on more ambitious projects.

originating PHP

    On the server, there is the original web page that the actual human being has arrived at.

    You need to output the JavaScript and surrounding web page. You can escape from the PHP and just send the actual HTML, CSS, and JavaScript files.

    There is one little bit of trickiness. Web browsers prevent cross platform scripts, because those can be used for all kinds of malicious software. You do need to tell the JavScript where to go on your webstie to pick up your new HTML. But is you hard code www.example.com and the browser visited example.com, then many web broswers will reject the incoming HTML as cross platform code. Any other combination of subdomains will also present the same problem.

    The solution is to use a little bit of PHP to insert the web address that the browser is using:

http://<?php echo $_SERVER['SERVER_NAME']; ?>/serverdispatch.php?action=update

    Otherwise, you just use a combination of PHP and regualr markup (HTML, CSS, JavaScript, etc.) to build the initial web page.

JavaScript

    I will be providing an extremely stripped down web page to help you see the parts you need for the AJAX.

    In this example, the JavaScript will fetch a bit of HTML from the server and insert it into the web page:

    We start with some session management. This will be the subject of another tutorial. You can leave this out or fill it out with your own working software.

<?php

// include function files for this application
require_once('./php/accounts.php');

/* SESSION MANAGEMENT */
SessionManagement(); /* located in accounts.php */
$accountemail = CheckValidUser(); /* located in accounts.php */
/* empty string if not signed in, or string holds the official account number */

?>

    Now we serve up the standard head stuff. Fill this out with keyword, description, and other meta tags as desired. Add in your own style sheet.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en" dir="ltr">
<head><title>SlamZee</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=ISO-8859-1"></meta>
<link rel="stylesheet" type="text/css" href="./style.css">

    In the head section we insert the all important JavaScript function that fetches the data from the server.

    Later in this document there is a “button” that triggers the loading of the information from the server.

    And later in this document there is the target of the new data, which is called “targetarea”.

    Start a JavaScript section.

<script type="text/javascript">
<!--

    Declare function. In this case we have a pair of parameters, the action code and an option code to send back to the server.

function fetchhtml(actioncode,secondcode) {

    The first thing we do is alert people that information is loading. It can sometimes take several seconds for data to route around the internet and you don’t want the visitor to keep pressing the action button because they don’t see anything happen. It is important to always give good feedback. The loading message is inserted into the targetarea. You can get as fancy in your HTML and CSS as you desire.

document.getElementById("targetarea").innerHTML="<p align=\"center\">loading information</p>";

    Next we set the URL that we will be reaching out to. This is on your own server. Notice that we are taking the action code and a second code as variable input to the function. In a more sophisticated version of this code, you can set these values on the server side during each exchange of data. This uses simple GET. It is much more complicated to get POST to work because you have to replace a whole lot of code that is normally handled for you by the web browser.

var serverurlstring = "http://<?php echo $_SERVER['SERVER_NAME']; ?>/serverdispatch.php?action="+actioncode+'&opton='+secondcode;

    We obtain an object for handling XML over HTTP requests (and save the handle in a variable for future use).

var myajaxobject = new XMLHttpRequest();

    We set the callback function that the object will use when the data returns. In the future, you can learn the methods for a variety of different state changes that you can handle.

myajaxobject.onreadystatechange=function()

    We test for success. A readyState of 4 and a status of 200 is success.

  {
  if (myajaxobject.readyState==4 && myajaxobject.status==200)
    {

    Once we have the data, we can simply insert it into the web page at the designated targetarea. Once you are comfortable with the exchange of data, you can start processing the response and do all kinds of cool things with real XML, JSON, etc.

      document.getElementById("targetarea").innerHTML= myajaxobject.responseText;
    } /* END IF */

    A little bit of debugging code. You probably don’t want this in your actual production software, but it can help you out while getting started.

  else if (myajaxobject.readyState==4) {newstring='code is '+ myajaxobject.status;
  document.getElementById("targetarea").innerHTML=newstring;
  } /* END of ELSE IF */

    End the callback function.

  } /* END callback function */

    Use the open method to prepare to contact the server. The parts here are the GET protocol, the URL to contact, and to run the function asynchoronously. Almost always run asynchronoously, or your web page will freeze up until the data returns.

    The asynchronous call allows your web page to respond to the user and allows you to run other JavaScript (possibly on a timer) while you wait for the information to come back from the server.

    When the data comes back from the server, the object will use the callback function you already set up.

myajaxobject.open("GET",serverurlstring,true);

    Now that everything is properly set-up, send your AJAX request.

myajaxobject.send();

    Close off your JavaScript function. Return value of false means normal completion.

return false;

} /* END FUNCTION fetchhtml */

    And close off the head section.

//-->
</script>
</head>

    Start the body section. This can be filled with whatever interesting things you have to show your visitors.

<body text="#ffffff" bgcolor="#000000">
</head>
<body>

<h1 align="center">Page Title</h1>

<div id="mainpage">

<div id="maincontent">

<p align="center">some content</p>

    Here is the famous targetarea. This is where your JavaScript function will insert the HTML you receive from the server.

<div id="targetarea">

</div><!--targetarea-->

    And here is the “button” to trigger your AJAX function. Note that there are a lot debates about links using javascript:void(0). That isn’t the point of this tutorial, so I am trying to keep things very simple.

<h3 align="center"><a href="javascript:void(0);" onclick="fetchhtml(1,'fresh');" style="cursor:pointer;">Update now!</a></h3>

    Close off the web page (probably with more cool content you want to share with the world.

</div><!--maincontent-->

</body>
</html>

server dispatcher

    Now we have the dispatcher on the server that responds to your AJAX requests.

    In theory you will end up with a bunch of different kinds of AJAX calls once you get comfortable with the technology. Instead of having a different webpage for every different kind of AJAX call, you can have one dispatcher page that analyzes the requests and dispatches the request to the correct handler.

    Standard beginning stuff, including require-Onces and globals.

<?php

/* FILE: /serverdispatch.php */

// include function files for this application
require_once('./php/accounts.php');
require_once('./php/databasefunctions.php');

/******************************/
/* GLOBALS                    */
/******************************/

    The functions. We have two different functions, each of which gives very simple sample HTML. You can get as fancy as you want once you are comfortable with these techniques.

/******************************/
/* FUNCTIONS                  */
/******************************/

/******************************/
/* ExcitingAction             */
/* some really cool action    */
/******************************/
function ExcitingAction($actioncode,$secondcode)
{

  echo '<h1 align="center">Fresh content direct from the server!</h1>';

} /* ExcitingAction */


/******************************/
/* AlternativeAction          */
/* alternative cool action    */
/******************************/
function AlternativeAction($actioncode,$optioncode)
{

  echo '<h1 align="center">More fresh content direct from the server!</h1>';

} /* AlternativeAction */

    The main page software.

/******************************/
/* Main Page                  */
/* serve various functions    */
/******************************/

    Some simple session management (beyond the scope of this tutorial) -- replace with your own or delete.

SessionManagement(); /* located in accounts.php */
$reporteduser = CheckValidUser(); /* located in accounts.php */

    gather the GET information sent from your JavaScript in the web browser.

/* INITIALIZATIONS */
if(empty($_GET))
  { /*go away if no valid requests */

    return;

  }
else
  { /*collect input from user */

    $actioncode = $_GET['action']; /* have a request for a specific action */
    $secondcode = $_GET['option']; /* have a request for a specific action */

  } /* END if on GET */

    The dispatcher. Based on the codes sent to the server, we choose which function to run. When you get a lot of these functions, organize them into their own PHP files.

    You can add as many GET variables as you desire, within unspecified limits. The typical web browser has a limit of around 2,048 characters (early browsers had a limit around 255 characters). Servers are supposed to handle URLs of unbounded length, but should return 414 (Request-URL Too Long) if the server can’t handle it. Some servers have a limit as low as 255 characters. If you need to send a lot of data, you need to learn how to use POST and possibly multi-part.

/* INITIALIZATIONS */
if(empty($_GET))
  { /*go away if no valid requests */

    return;

  }
else
  { /*collect input from user */

    $actioncode = $_GET['action']; /* have a request for a specific action */
    $optioncode = $_GET['option']; /* have a request for a specific action */

  } /* END if on GET */

conclusion

    I hope that this is useful. This stuff is surprisingly easy.

comments

    I know I am going to get a bunch of comments pointing out every error I’ve ever made. And suggestions for some basic improvements I’ve overlooked. That’s OK. Please send them in. I will give you credit and this webpage will be much better for the public because the crowd working on open source software is always better than closed proprietary software.

copy and paste version of JAVASCRIPT

    It is easy to confuse the PHP and the JavaScript. Rememebr that the PHP runs on the server and the JavaScript runs on the browser.

    This PHP file produces all of the HTML, CSS, and JavaScript for the web browser.

<?php

// include function files for this application
require_once('./php/accounts.php');

/* SESSION MANAGEMENT */
SessionManagement(); /* located in accounts.php */
$accountemail = CheckValidUser(); /* located in accounts.php */
/* empty string if not signed in, or string holds the official account number */

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en" dir="ltr">
<head><title>SlamZee</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=ISO-8859-1"></meta>
<link rel="stylesheet" type="text/css" href="./style.css">
<script type="text/javascript">
<!--

function fetchhtml(actioncode,secondcode) {
document.getElementById("targetarea").innerHTML="<p align=\"center\">loading information</p>";
var serverurlstring = "http://<?php echo $_SERVER['SERVER_NAME']; ?>/serverdispatch.php?action="+actioncode+'&opton='+secondcode;
var myajaxobject = new XMLHttpRequest();
myajaxobject.onreadystatechange=function()
  {
  if (myajaxobject.readyState==4 && myajaxobject.status==200)
    {
      document.getElementById("targetarea").innerHTML= myajaxobject.responseText;
    } /* END IF */
  else if (myajaxobject.readyState==4) {newstring='code is '+ myajaxobject.status;
  document.getElementById("targetarea").innerHTML=newstring;} /* END of ELSE IF */
  } /* END callback function */
myajaxobject.open("GET",serverurlstring,true);
myajaxobject.send();

return false;

} /* END FUNCTION fetchhtml */

//-->
</script>
</head>

<body text="#ffffff" bgcolor="#000000">
</head>
<body>

<h1 align="center">Page Title</h1>

<div id="mainpage">

<div id="maincontent">

<p align="center">some content</p>

<div id="targetarea">

</div><!--targetarea-->

<h3 align="center"><a href="javascript:void(0);" onclick="fetchhtml(1,'fresh');" style="cursor:pointer;">Update now!</a></h3>

</div><!--maincontent-->

</body>
</html>

copy and paste version of PHP

<?php

/* FILE: /serverdispatch.php */

// include function files for this application
require_once('./php/accounts.php');
require_once('./php/databasefunctions.php');

/******************************/
/* GLOBALS                    */
/******************************/


/******************************/
/* FUNCTIONS                  */
/******************************/

/******************************/
/* ExcitingAction             */
/* some really cool action    */
/******************************/
function ExcitingAction($actioncode,$secondcode)
{

  echo '<h1 align="center">Fresh content direct from the server!</h1>';

} /* ExcitingAction */


/******************************/
/* AlternativeAction          */
/* alternative cool action    */
/******************************/
function AlternativeAction($actioncode,$secondcode)
{

  echo '<h1 align="center">More fresh content direct from the server!</h1>';

} /* AlternativeAction */


/******************************/
/* Main Page                  */
/* serve various functions    */
/******************************/

SessionManagement(); /* located in accounts.php */
$reporteduser = CheckValidUser(); /* located in accounts.php */

/* INITIALIZATIONS */
if(empty($_GET))
  { /*go away if no valid requests */

    return;

  }
else
  { /*collect input from user */

    $actioncode = $_GET['action']; /* have a request for a specific action */
    $secondcode = $_GET['option']; /* have a request for a specific action */

  } /* END if on GET */

/* dispatch based on what game activity requested */
if ( $actioncode == '1' )
  ExcitingAction($actioncode,$optioncode);
elseif ( $actioncode == '2' )
  AlternativeAction($actioncode,$optioncode);

?>

return to explanation of source code


OSdata.com is used in more than 300 colleges and universities around the world

Find out how to get similar high web traffic and search engine placement.


OSdata.com is used in more than 300 colleges and universities around the world

Read details here.


    A web site on dozens of operating systems simply can’t be maintained by one person. This is a cooperative effort. If you spot an error in fact, grammar, syntax, or spelling, or a broken link, or have additional information, commentary, or constructive criticism, please e-mail Milo. If you have any extra copies of docs, manuals, or other materials that can assist in accuracy and completeness, please send them to Milo, PO Box 1361, Tustin, CA, USA, 92781.

    Click here for our privacy policy.


previous page next page
previous page next page

home page


Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser


    Names and logos of various OSs are trademarks of their respective owners.

    Copyright © 2013 Milo

    Last Updated: October 14, 2013

    Created: October 14, 2013

previous page next page
previous page next page