All posts tagged Development

Two AJAX Walkthroughs: a File Fetcher and MySQL Fetcher

AJAX (Asynchronous JavaScript and XML) is one of the coolest things you can do with JavaScript: it lets you update web pages after they’re loaded. This process might not mean much to you if you’re thinking only as a programmer. But, think about the convenience AJAX delivers to your typical web user: less waiting.

When you combine an AJAX-powered JavaScript page with PHP, you can pull in data from any part of the web — a great way of detouring the same-domain security restriction hard-coded into browsers. But you can also complete important tasks with just JavaScript code.

Fetch web content from your site

Try this example script, which fetches the content of a web page whose filename is entered by the user in an HTML text box. The AJAX phenomenon will be immediately apparent when you open this page in your browser: as you’re typing the filename, the JavaScript makes asynchronous (AJAX) requests to the server to fetch the file’s content and then displays that content.

Let’s shoot first and ask questions later. Here’s the code:

<html>

<head>

<script type=&quot;text/javascript&quot;>

var obPageFetcher=null;

function fetchPage() {

    var sUrl = document.getElementById(&quot;filename&quot;).value;

    obPageFetcher=new XMLHttpRequest();

    obPageFetcher.onreadystatechange=function () {

if (obPageFetcher.readyState==4) {

/* A readyState of 4 means

&quot;all data has been received.&quot;

See the &quot;XMLHTTPRequest object&quot; on MSDN.com

*/

if (obPageFetcher.status==200){

/* A status of 200 means

&quot;OK,&quot; successful request.&quot;

See above note.

*/

document.getElementById('divContent').innerHTML=

obPageFetcher.responseText;

} else {

document.getElementById('divContent').innerHTML=

obPageFetcher.statusText;

}

}//on readyState==4

}//state_Change call back;

obPageFetcher.open(&quot;GET&quot;,sUrl,true);

obPageFetcher.send(null);

}// fetchPage()

</script>

</head>

<body>

<input onkeyup=&quot;fetchPage()&quot; type=&quot;text&quot; id=&quot;filename&quot;

style=&quot;border-color:blue&quot; size=&quot;40&quot;

value=&quot;http://www.<TYPE_YOUR_DOMAIN_NAME_HERE>.com/index.htm&quot;>

<br>

<div id=&quot;divContent&quot; ></div>

</body>
</html>

You’ll need a web hosting service to upload this page to. Once you have one, enter your domain’s name in place of the text in the script.

Run this script by uploading it to your web host’s server, then download the page into your browser. Start typing in the text box and you’ll notice immediately that the content changes based on what you’re typing. Enter in valid filenames for files in your domain (e.g. “index.htm”) and the script will load the HTML content of those files into your page below the text box.

How it works

We’ll get to the sexy AJAX stuff in a moment, but let’s look at the code’s parts in a logical order. First, notice the page’s main DOM (document object model) elements inside the tag: there’s only a text box
and a

,/code> to hold the fetched content.

The
element has an event listener attached to its “onkeyup” event; every time you lift your finger off any key while in the text box, that event listener function (fetchPage) is going to be called. So far, there’s nothing AJAX-y about the code, but that’s coming in the fetchPage() function.

Fetch page

The fetchPage callback function’s main job is to prepare for and then make the asynchronous request to the server. To do this preparation, fetchPage needs to tell the XMLHTTPRequest object, which does the actual asynchronous request, what function to call when the server responds. In other words, fetchPage is defining a callback function to hand to the XMLHTTPRequest object. You can see that function in the statement obPageFetcher.onreadystatechange=function…. (If this statement looks goofy to you, don’t blame AJAX, but JavaScript, which allows nameless (AKA “anonymous”) functions in its syntax.)

The guts of the callback function

The callback function checks on a couple of status properties (“readyState” and “status”) before assigning the real guts of the server response, inside property “responseText,” to the output DOM element mentioned earlier (“divContent”). Describing the callback function first is a bit like putting the egg before the chicken, in terms of program execution: on the first call to fetchPage, we’re only defining the anonymous callback function, not actually calling it. After we define the callback function, we open up (statement “obPageFetcher.open(…)” ) and send (statement “obPageFetcher.send(…)”) the request to the server.

Example two: Use AJAX to do a database pull

If you know how to do a basic SELECT fetch from a MySQL database using PHP, you can apply that knowledge to do the fetch asynchronously with AJAX. If you’re not MySQL savvy yet, don’t fret: see the Resources section of this article to get the know-how. Plus, do get the details of connecting to your MySQL database from the tech support people at your web host–you’re paying them to support you.

Create a “movies” table on a MySQL database on your server. Define the fields in the table as follows:

  • title: varchar(30)
  • director: varchar(30)
  • year: int

Enter the following sample data in that table, corresponding to the fields just given. Don’t enter the commas.

  • star wars, lucas, 1977
  • excalibur, boorman, 1980

Create a PHP script from the following code and call the script “phpMySQLFetch.php”

Upload the file to your server, then make the following changes to the AJAX script given earlier:

<?php

mysql_connect(&quot;<YOUR_MYSQL_DATABASE_NAME>&quot;, &quot;<YOUR MYSQL LOGIN>&quot;, &quot;<YOUR MYSQL PASSWORD>&quot;) or die(mysql_error());

mysql_select_db(&quot;<YOUR DATABASE NAME>&quot;) or die(mysql_error());

$sTitle = $_GET[&quot;title&quot;];

$sqry = 'SELECT * FROM `movies` WHERE `title` LIKE CONVERT(_utf8 \'%'.$sTitle.'%\' USING latin1) COLLATE latin1_swedish_ci';

$data = mysql_query($sqry)

or die(mysql_error());

while($info = mysql_fetch_array( $data ))

{

Print $info['title'].&quot;, &quot;.$info['director'].&quot;, &quot;.$info['year'].'<br>';

}

?>

Change the fetchPage function in the HTML page so it starts like this:

function fetchPage() {
    sUrl = "phpMySQLFetch.php?title=" +
    document.getElementById('title').value;
    ... // The rest is the same as the first example

Change the element to look like this:

<body >
<input type=&quot;text&quot; size=&quot;40&quot; name=&quot;title&quot; id=&quot;title&quot; onkeyup=&quot;fetchPage()&quot;>
<br>
<div id=&quot;divContent&quot; ></div>
</body>

Upload the revised HTML page to the same folder on your server that contains the PHP script, then download the HTML page into your browser. Start typing the names of one of the movies (e.g. “star wars,” “excalibur”) in the text box, and watch the AJAX code dynamically fill in the page with the rest of the info for that movie.

Experiment

As mentioned before, combining PHP server code with JavaScript will really show you the power of AJAX, because the PHP can go into the proverbial “where no man has gone before,” — all over the web, in other words, to fetch content. To get started with that, start digging into PHP by reading Introduction to PHP . Then, adapt the script in this article so that it calls and retrieves content from your PHP script.

References

W3Schools’ AJAX Tutorial

Resources

PHP MySQL Tutorial

Introduction to PHP (PHP: Hypertext Preprocessor)

Introductions

Article Scope

This article aims to express the basics, which a beginner should consider when learning PHP. It will explain how to create a very basic PHP page that will contain fundamental commands to PHP beginners.

For this article, I will be using XAMPP to execute my PHP code – this is free to download and is great, especially if you do not have a web server with PHP installed.

PHP Introduction

PHP is open source software and therefore it is free to download and use. PHP’s website is: http://www.php.net/ (where it is also available for download).

PHP is a powerful HTML‐embedded scripting language, which allows web developers to write dynamically generated pages. The user does not see the PHP code, unlike HTML ‐ instead, the server executes the PHP code (written by you) when the user requests it. Once executed, PHP will use HTML to output – which is determined by you, and thus you will need to have an understanding of HTML for HTML to be of any use to you.

PHP is widely used in conjunction with MySQL, which will be explained in a future article.

Benefits of using PHP

PHP will reduce time to create and maintain medium to large websites – due to the pages being dynamic, only a small number of PHP pages will need to be created/edited which will allow the use of a Database (commonly MySQL), containing the websites’ content. The contents of the database are extracted by PHP and a page is created “on-the-fly”.

A few more of PHP’s benefits are shown below:

  • Allow the website to customize each users experience, based on information gathered from them.
  • Create websites that allow users to purchase items off a website (known as ecommerce).
  • PHP users can download and use many free Open Source PHP tools on their website.
  • As PHP is executed on the server this means that the PHP is not dependent on the users’ computer settings. For example, a user requesting a page in Firefox will get the same PHP Output as that of a user viewing in Internet Explorer, but please bear in mind that the way the HTML/CSS output is formatted may differ between the two. You will most likely have met this if you have used HTML/CSS to an intermediate level.
  • All PHP’s commands are described and examples given in the PHP Online Manual.

Syntax

Create a PHP File

The first thing that all developers need to do is create a blank PHP page. This can be done by simply opening up Notepad and creating a new file – but instead of saving it with the ‘.txt’ affix, change it to ‘.php’. Alternatively, users that have dedicated editors such as Dreamweaver, etc. can create a blank PHP page by selecting File menu and create new PHP page.

Now that we have our blank PHP page we can begin.

Tell the server we wish to begin

We have to tell the server that we wish to execute PHP code, otherwise when the user requests the page, nothing dynamic will happen and instead it will just show our PHP code as plain text.

We use ‘‘ to end. The ‘‘ to end executing our PHP code. Outside of these brackets is where our HTML code should go which should not be dynamically updated, such as our Headers, Footers, etc.

You can use the shorthand PHP beginnings (‘‘) but this is not recommended as servers do not always support these.

PHP Comments

We place comments in PHP code to make the code more maintainable and readable. These comments will not be viewable to the public, only to the person editing the PHP file. To comment in PHP we should prefix ‘//’ to our comment, for example:

<?php
     //This is our comment
?>

We can also place comments over multiple lines by using ‘/*’ to begin and ‘*/’ to end our comment – as shown below.

<?php
      /* This is a
      comment set
      over multiple
      lines*/
?>

Comments will be a lot more useful when more advance techniques in PHP are used.

A basic page in PHP is shown below, using our start, and end tags as well as comments. Please note that nothing will show, as comments are being used.

<html>
<head>
    <title>First PHP Comments</title>
</head>
<body>
    <?php
    // This is a comment and will not be shown to the public

    /* This is a multi‐line comment and will not be shown
       to the public */

    ?>
</body>
</html>

Semicolons

Semicolons are used extensively in PHP. The semicolon generally (there are exceptions) signifies the end of a PHP statement and should not be forgotten, otherwise unsightly errors will occur. An example will be shown in the Outputting HTML code using PHP section.

Outputting HTML code using PHP

Outputting HTML code using PHP is extremely easy. It can be done using the PHP Print command or indeed PHP Echo. The difference between the two commands can be read on the PHP FAQ’s site.

Below is how to output “This is my first output PHP string” in HTML paragraph and bold tags. This example will also show how the semicolon is used (read prior section,Semicolons).

<html>
<head>
    <title>My first PHP outputs</title>
</head>
<body>
    <?php
    print &quot;<p><strong>This is my first output PHP
   string</strong></p>&quot;;
    // For consistency I will show the use of the echo command
    echo&quot;<p><strong>This is my first output PHP
   string</strong></p>&quot;;
    ?>
</body>
</html>

If you run the above code, you will see that you get the output:

The first line is of the print command and the second line is the output of the echo command. Please note that there is no difference between the two. Please also note the usage of quotation marks – these are used to tell the PHP code that we wish not to execute the contents contained within.

PHP Variables

Variables are important to PHP. A variable is a way of storing a value, such as text (“Hello”), numeric values (such as the integer value of 1) and also Boolean values (true and false). A variable can be re‐used throughout your code instead of typing out the value over and over again. Variables will also not be new to you if you’ve had any experience of Algebra in Mathematics.

You define a variable in PHP like so:

<?php
    $name=“Marc Fraser”;
    $age=16;
?>

The first things you should notice is the dollar sign ($). In PHP this signifies that the item is a variable, I can name a variable whatever I wish such as $a, $b, $c, as long as I do not omit it – otherwise syntax errors will occur. At this time, you should also note that variables are case sensitive, therefore $a is different in the eyes of PHP than $A.

Once our data is stored in a variable, we can perform operations to it, such as print, string manipulation and if the variable is an integer, calculations can be done. Below is how to print a variable:

<?php
    $name=“Marc Fraser”;
    $age=16;

    print$name;
    print$age;
?>

The above will output “Marc Fraser16”.

Variable naming conventions:

  • PHP Variables may only start with a letter or underscore (_).
  • Spaces are not permitted in PHP variables and so underscores, or
    capitalization should be used – such as: $this_variable, $thisVariable.
  • Variables may only comprise of alphanumeric characters.

PHP Concatenation

We can display our variables in a meaningful fashion with the use of concatenation. Concatenation makes use of the period (.). Please see the example below which is an example of affixing a value to the end of the variable:

<?php
    $name=“Marc”;
    $name.=“Fraser”;
?>

Basically what ‘.=’ is doing is saying use the current value of $name and add “Fraser” to the end of it. If I were to now print $name, it would output “MarcFraser”.

We can also use concatenation to create readable sentences:

<?php
    $name=“Marc Fraser”;
    $age=16;

    print “We would like to welcome you,”.$name.“,age”.$age.“to
    our website!”;
?>

This will output “We would like to welcome you, Marc Fraser, age 16 to our website!”. To do this, we close the string (close quotation mark) and add our period, which tells the server that we wish to begin parsing PHP again. When we want to stop parsing PHP we add a period and then begin our string again (quotation mark).

PHP Operators

Here are most types of PHP Operators: Assignment Operators, Arithmetic Operators, Comparison Operators, and String Operators.

Assignment Operators

We have already met this type. This is where we set a variable equal to something or make a variable equal to another variable.

Arithmetic Operators

English Operator Example
Addition + 1+1
Subtraction - 5-3
Multiplication * 5*2
Division / 10/2

An example of the use of Arithmetic operators is shown below:

<?php
    $add=1+1;
    $subtract=5‐3;
    $multiply=5*2;
    $divide=10/2;

    print“Addition Answer:” .$add.“<br>”;
    print“Subtraction Answer:”.$subtract.“<br>”;
    print“Multiplication Answer:”.$multiply.“<br>”;
    print“Addition Answer:”.$divide.“<br>”;
?>

The output of the above code is:

Addition Answer: 2

Subtraction Answer: 2

Multiplication Answer: 10

Addition Answer: 5

This showing that the server is carrying out the calculations, using our arithmetic operators. As well as the above, you could also use these operators in conjunction with each other like so:

<?php
    $quantity=4;
    $value=5;
    $total=$quantity*$value;
    print$total;
?>

The output from the above is 20.

Comparison Operators

Comparison Operators are used to check the relationship between variables/values. These are used inside statements (such as if statements) to check whether the result is true or false. Listed are some PHP comparison operators:

We will assume, for this example, that $a = 2 and $b = 3.

English Operator Example Result
Equal to == $a == $b False
Not equal to != $a != $b True
Less than < $a < $b True
Greater than > $a > $b False
Less than or equal to <= $a <= $b True
Greater than or equal to >= $a >= $b False

Please note the two equal signs in the equal to example – this is a common beginners’ mistake.

We will go into further examples of Comparison Operators in the next section on PHP If Statements.

String Operators

We have already met String Operators, please read prior section named Concatenation.

PHP If Statements

In PHP IF statements are extensively used. It allows you to show the user data depending on certain conditions. The best way to describe it is with the use of an example: You want to build a dashboard with items you do not want all employees
to see, this is where IF statements come in handy – you can check that they are a certain person or a member of a certain group and if this is true the employee can see the item, if it is false (the employee isn’t in the necessary group) then the employee shouldn’t see the items.

We will use Comparison Operators in the example below;

<?php
    $isManagement=false;

    if($isManagement == true){
    // Show the data that you wish only management to see.
    } else{
    // You are not management and so cannot see this data.
    }
?>

The above example uses comments to show how the if statement works in terms of the example farther above. $isManagement will come from the employees record.

Within the IF() statement we are comparing to see if $isManagement is true, within the first parenthesis ({}) is where the PHP code will go if the result is true. The else statement is included to catch all other occurrences apart from the true occurrences. Please see the PHP Manual for another example.

PHP Include

The include command can save you a lot of time as you can create a header, place it in a file and just include that file on every page and the header will be shown. This will also mean that you do not need to edit every page every time you need to edit your header!

Basically the PHP Include command takes the file name and inserts the contents of the file into the script.

To illustrate this, I will use an example:

  1. Create a HTML file called Menu.html and insert the following code into it:
  2. <ul>
            <li>Home</li>
            <li>Articles</li>
            <li>Tutorial</li>
    </ul>
  3. Now create a menu_example.php PHP file (in the same directory as
    Menu.html) and insert:
  4. <?php
        include(‘Menu.html’);
    ?>
  5. Navigate to menu_example.php in your browser and run it – you should see:

Thank you for reading my Introduction to PHP and hope it enlightens you to the basics of PHP Server‐Side coding.