Tag Archives: Scripting

Web development #7: Dynamic page updates with AJAX

So in theory you should now have all the tools to create the most awesome websites. However, I don’t think any tutorial on web development is complete without doing some AJAX. No idea what I’m talking about? Read my previous posts.

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

So what is AJAX all about? It’s an abbreviation for Asynchronous JavaScript And XML. It enables us to send a request to the server and receive a result without having to refresh our entire page. Now that’s pretty awesome! What’s also pretty awesome is that we don’t need to use XML. As Linus Torvalds, creator of Linux, already said “XML is crap. Really. There are no excuses. XML is nasty to parse for humans, and it’s a disaster to parse even for computers. There’s just no reason for that horrible crap to exist.” So what we’ll be using is a form of AJAX called AJAJ, where the last J stands for JSON (JavaScript Object Notation). To make it a bit more confusing, we’ll just call it AJAX anyway. Oh yeah, and it doesn’t have to be asynchronous either…

JavaScript objects and JSON

First of all we need to know what JavaScript Objects are and what they look like. After that JSON will come naturally. So JavaScript has objects and much like objects in other languages JavaScript objects are just wrappers around certain functionality. The difficulty in JavaScript, of course, lies in that anything can be anything and then can become anything else… Let’s just look at an example.

// Creates an empty object.
var obj = {};
// Gives the object a firstName property.
obj.firstName = 'Sander';
// Gives the object a lastName property.
obj.lastName = 'Rossel';
// Gives the object a getFullName function.
obj.getFullName = function () {
    return this.firstName + ' ' + this.lastName;
};

// Alternative for the above.
var person = {
    firstName: 'Sander',
    lastName: 'Rossel',
    getFullName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};

Now this wouldn’t be JavaScript if we didn’t have even more methods to create objects (JavaScript also knows constructors). We’re not interested in those though. What we’re interested in is the second method I’m using. Notice that, to create an object, we use curly braces. We can then basically add anything to that object by simply defining keys (property or function names) and values (default values for properties or implementations for functions) seperated by colons. Each key and value is seperated by a comma. And of course objects can contain other objects too.

var outerObj = {
    innerObj: {
        someValue: null
    },
    anotherInnerObj: {
        innerInnerObj: {}
    },
    message: 'Phew, what syntax!'
};

You can work with objects as ways of namespaces so you can keep the ‘global namespace’ clean and minimize the chance for name conflicts with other libraries. Objects are also often used to create some sort of options that are given to a function. A function then simply checks if some property or method on the option object exists, what its value is, and acts accordingly. We’ll see this usage a little later when working with AJAX.

So then, what is JSON? It’s simply some text using almost the exact notation we just saw. So let’s look at some examples.

{
    "firstName": "Sander",
    "lastName": "Rossel"
}

{
    "innerObj": {
        "someValue": null
    },
    "anotherInnerObj": {
        "innerInnerObj": {}
    },
    "message": "Phew, what syntax!"
}

That’s looking pretty familiar now, doesn’t it? And, if you compare it to XML, it’s a lot more compact, saving you precious bits and bytes when you’re sending your data over the internet!

Making an AJAX request

So let’s look at an AJAX example. I’ll start very simple making a synchronous request that returns just plain text (so no XML or JSON) when the page loads. You’ll know that the request doesn’t refresh the page because if it would the page would keep refreshing (as it makes the request upon loading). Alternatively, you can track all requests your browser makes using your browsers developer tools (press F12 in IE, FireFox or Chrome and navigate to the Network tab). I’m using jQuery to get the page load event and to show the result of our AJAX request. So here’s the HTML (in a file called Ajax.html):

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="Ajax.js"></script>
    </head>
    <body>
        <p id="result"></p>
    </body>
</html>

Here’s our JavaScript (Ajax.js):

$(function () {
    var ajax = new XMLHttpRequest();
    ajax.open('GET', 'Ajax.php', false);
    ajax.send();
 
    $('#result').text(ajax.responseText);
});

And finally our PHP (Ajax.php):

<?php
    echo 'Result of AJAX request!';
?>

So all of these files go into the htdocs folder of your XAMPP installation and you’ll have to access your page by browsing to localhost/Ajax.html (notice I named all files ‘Ajax’). So what’s really interesting here is that in my JavaScript I’m using an XMLHttpRequest object. So we call the open method and pass in a string specifying the HTTP method, GET or POST. Next we’re telling it what URL to navigate to and last we’re specifying whether the request should be asynchronous (we’re calling it synchronous). Then we send the request to the server. So, because we’re calling it synchronous the browser blocks until we get response from the server. That means that on our next line of code we simply have our result, ajax.responseText. Now you’ll never do this, in fact, our browser even gives off a warning saying that this method is deprecated because it negatively affects the user experience. In our case we won’t notice the blocking, but if we’re downloading larger chunks of data our page will freeze up completely!

So let’s make that call asynchronous so the user can go about doing his business while our page gets our data for us. This isn’t actually to hard. We simply change our JavaScript to the following:

$(function () {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            $('#result').text(ajax.responseText);
        };
    };
    ajax.open('GET', 'Ajax.php', true);
    ajax.send();
});

So I’m specifying an onreadystatechange function which gets called when the state of our ajax object changes. State 4 means it’s done and we can get the result.

Now there are quite some options we can set and check, but I’ll not get into that. You can check them on the XMLHttpRequest documentation page and play around with them yourself. Instead, we’re going to use jQuery to make AJAX requests.

Using jQuery for AJAX requests

You might be thinking if there’s anything jQuery cannot do? There’s actually plenty of stuff you don’t want to do using jQuery, but AJAX isn’t one of them. jQuery makes AJAX pretty easy actually. We were already using jQuery, so we can simply edit our JavaScript.

$(function () {
    $.ajax({
        type: 'GET',
        url: 'Ajax.php',
        complete: function (jqXHR) {
            $('#result').text(jqXHR.responseText);
        }
    });
});

So remember I was telling you about using an object to specify options? This is one such an example. We’re passing in an object and specify the type, the url and a function that will be called when the requests completes (jqXHR stand for jQuery XMLHttpRequest, but you can name it anything). We could’ve passed in much more, but we didn’t. So this does the same as the code we had earlier.

The jQuery.ajax function can actually do a whole lot of stuff! Next we’re going to pass in some parameters and echo them on our page.

$(function () {
    $.ajax({
        type: 'GET',
        url: 'Ajax.php',
        data: {
            artist: 'Led Zeppelin',
            song: 'Immigrant Song'
        },
        complete: function (jqXHR) {
            $('#result').text(jqXHR.responseText);
        }
    });
});

And now we need to alter our PHP too.

<?php
    if (isset($_REQUEST['artist']) &&
        isset($_REQUEST['song']))
    {
        $artist = $_REQUEST['artist'];
        $song = $_REQUEST['song'];
        echo "The song '$song' by $artist rocks!";
    }
?>

So that was pretty easy, right? We just passed in a JavaScript object with some properties and they were converted to parameters in our PHP automatically! So how does this work the other way around? This is where JSON comes into play! JSON stands for JavaScript Object Notation, so it should be pretty easy for JavaScript to create actual objects that we can use. So let’s start by modifying our PHP so that it returns JSON.

<?php
    class song
    {
        public $artist = NULL;
        public $name = NULL;
    }
 
    if (isset($_REQUEST['artist']) &&
        isset($_REQUEST['song']))
    {
        $song = new song();
        $song->artist = $_REQUEST['artist'];
        $song->name = $_REQUEST['song'];
 
        header('Content-Type: application/json');
        echo json_encode($song);
    }
?>

First of all, I’m using an object to store our data. We’ve seen this before. I’m setting our response header so that it tells our browser it’s json. Then I’m using the json_encode function to convert our object into JSON. If you now check out the result in your browser you’ll notice that we’ve received some actual JSON!

But what we really want is to use this JSON in our JavaScript as if it were just an object. Actually this is pretty easy! We can get the object from the XMLHttpRequest.

complete: function (jqXHR) {
    var song = jqXHR.responseJSON;
    $('#result').text("The song '" + song.name + "' by " + song.artist + " rocks!");
}

And that’s it. Alternatively, we can use the ‘success’ option, a function that passes us the returned data, the status of the request and the XMLHttpRequest.

$(function () {
    $.ajax({
        type: 'GET',
        url: 'Ajax.php',
        data: {
            artist: 'Led Zeppelin',
            song: 'Immigrant Song'
        },
        success: function (song, status, jqXHR) {
            $('#result').text("The song '" + song.name + "' by " + song.artist + " rocks!");
        }
    });
});

And likewise there is an ‘error’ option.

$(function () {
    $.ajax({
        type: 'GET',
        url: 'Ajaj.php',
        data: {
            artist: 'Led Zeppelin',
            song: 'Immigrant Song'
        },
        success: function (song, status, jqXHR) {
            $('#result').text("The song '" + song.name + "' by " + song.artist + " rocks!");
        },
        error: function (jqXHR, status, errorThrown) {
            $('#result').text('An error occurred: ' + jqXHR.status + ' ' + errorThrown);
        }
    });
});

Notice that I’m calling ‘Ajaj.php’, a page that doesn’t exist. Naturally we’ll get 404, Not found. When using the ‘complete’ option we used earlier you’d have to check for success yourself, our current implementation would actually break our page if we called ‘ajaj.php’.

So there’s actually quite a bit to think about when using AJAX. Did the server return a result, what kind of result did it return, was the request successful, etc. We can use the XMLHttpRequest object for this. Check ‘status’ to see if our request was successful (status 200 means success) and then ‘responseType’ and any of ‘response’, ‘responseText’, ‘responseJSON’ or ‘responseXML’ for the result.

Posting data

So in the previous examples we’ve taken a look at the GET method. In the next example I’m going to take our movies page we created in my previous blog posts, Web development #4: PHP in the back and Web development #5: User input with HTML Forms. So first of all we’ll have to edit the PHP file. We want the form to go, because that refreshes the page. We also want to add jQuery and a custom JavaScript file to our header. Last, we need to give some ids to some elements because now we need to update the page ourselves once we add a new movie (after all, the page isn’t refreshing). So without further delay, here’s the modified PHP.

<?php
    if (isset($_POST['movieName']))
    {
        $movieName = $_POST['movieName'];
        if ($movieName)
        {
            file_put_contents('movies.txt', htmlspecialchars($movieName) . "rn", FILE_APPEND);
        }
 
        exit();
    }
?>
<!DOCTYPE html>
<html>
    <?php
        function fileAsUnorderedList($fileName, $notFoundMessage)
        {
            if (file_exists($fileName))
            {
                echo '<ul id="movies">';
                $lines = file($fileName);
                foreach ($lines as $line)
                {
                    echo '<li>' . htmlspecialchars($line) . '</li>';
                }
                echo '</ul>';
            }
            else
            {
                echo $notFoundMessage;
            }
        }
    ?>
    <header>
        <title>My favourite movies!</title>
        <meta charset="utf-8">
        <meta name="description" content="A list of my favourite movies.">
        <meta name="keywords" content="Favourite,movies">
        <meta name="author" content="Sander Rossel">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="Movies.js"></script>
    </header>
    <body>
        <h1>My favourite movies!</h1>
        <p>
        <?php
            fileAsUnorderedList('movies.txt', 'No favourite movies found!');
        ?>
        </p>
        <h2>Add a movie!</h2>
        <div>
            <label for="movieName">Movie name</label>
            <input type="text" name="movieName" id="movieName" />
            <button id="submit">Submit</button>
        </div>
    </body>
</html>

And then we need to add a JavaScript file (I’ve called it Movies.js) to add an event handler to our button click event which takes the value of the input, posts it to the server and on success adds the movie to our list and empties the movie input.

$(function () {
    $('#submit').on('click', function () {
        var movieInput = $('#movieName');
        var movieName = movieInput.val();
        if (movieName) {
            $.ajax({
                type: 'POST',
                url: 'Movies.php',
                data: {
                    movieName: movieName
                },
                success: function (data, status, jqXHR) {
                    $('#movies').append('<li>' + movieName + '</li>');
                    movieInput.val(null);
                },
                error: function (jqXHR, status, errorThrown) {
                    alert("An error occurred while adding movie '" + movieName + "'.");
                }
            });
        };
    });
});

And there you have it. Looks complicated? I guess it is a bit, but once you get the hang of it it’s not so bad. And luckily the documentation is rather good!
Another cool addition to our page would be pagination. Let’s say we are going to add hundreds of movies. Getting those all in once might slow down our page quite a bit. So we can use AJAX to get just ten, or twenty, or fifty at a time. The page could load them on a button click or when we scroll to the end of the page (that is, get the movie titles and add them to our list using jQuery, also make sure you ‘remember’ what page you’re on). This principle is called pagination and can greatly enhance user performance (and for large websites it’s even a must).

So that’s it for AJAX. And actually, that’s it for web development! You’ve now seen everything involved in creating awesome, responsive web pages. Of course there’s still a long way to go as we’ve only scratched the surface of web development. We’ve seen the tools, but are by no means expert in any of them. In my next, and last, blog post I’ll give you some tips on frameworks and libraries that can help you create the pages you want.

Stay tuned!

Web development #6: Getting interactive with JavaScript

We’ve come pretty far by now! We’re almost there actually. After reading this post you should be able to create pretty awesome websites using the full web development stack! So what’s left for us to discover? We have seen we can build dynamic websites on the back end using PHP, but what about being dynamic once the page is loaded? Well that’s where JavaScript comes into play!

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

The websites we’ve build were all pretty amazing. We’ve started simple using just HTML, added some CSS, then we added some dynamic content and we could even upload our own content. I don’t know about you, but I think that’s pretty amazing. However, I still feel like our pages are missing a little… schwung! How about highlighting buttons, sliding content in and out of our page? Just some fancy visuals that will make our website stand out. JavaScript comes to the rescue.
As an added bonus we can make calls to our back end without refreshing the entire page using AJAX. More on that later, let’s look at some fundamentals first.

JavaScript fundamentals

JavaScript has been around since 1995. It’s easy to learn, but hard to master. I’m not going to spend a lot of time on the syntax because it looks (and behaves) a lot like PHP, including truthy and falsey). I’m just going to write code. Try to keep up. I’m still writing in Notepad++ by the way. We also won’t be needing XAMPP to run basic JavaScript in this post (we’ll be needing it later for AJAX though).

One thing you should know about JavaScript is that, like CSS, it can be embedded into your HTML. But we don’t want that. In my post about CSS we learned to keep HTML and CSS seperated, which makes it easier for you to remodel your page by simply replacing some CSS files. We’ll use the same approach for JavaScript.

So let’s take a look at our first example. Yes, it’s going to be Hello world! Not the most exciting example, but you’ll see JavaScript in action. So we start out by creating a very simple HTML file. Call it whatever you like.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <button onclick="sayHello();">Press me!</button>
        <p id="output"></p>
    </body>
</html>

And now in the same folder create a file called MyJS.js. Inside it put the following code:

function sayHello () {
    var output = document.getElementById('output');
    output.innerHTML = 'Hello JavaScript!';
}

So let’s look at both the HTML and JavaScript. First in the header of the HTML you’ll notice I’ve added a script element. In this element I define the type and src attributes. Pretty straightforward I think. Your HTML now simply loads the specified JavaScript. In an actual server-client environment this means that the JavaScript files are sent to the client together with the HTML page.
Other than that we see a button element with an onclick event. Now whenever the user presses a button an event fires. An event is simply a notification you can subscribe to. In this case we subscribe by specifying onclick and telling it we want the function sayHello to be executed.

Now this function, sayHello, is defined in our MyJS.js file. It does the following. We declare a variable called ‘output’ using the var keyword. We assign it the result of a function called getElementById that takes a string as input parameter and is defined on something called document. Now your document is a variable that your browser gives to you and it represents your HTML content. So we’re almost literally saying “document, give me the element with id ‘output'” and guess what it returns? Yes, our p element with id ‘output’! Now that we have our paragraph we can alter it any way we see fit. In this case I’m simply going to give it the text “Hello JavaScript!”.
There’s more functions like getElementById, like getElementsByName() and getElementsByClassName(). Once you have an element you can get its child elements (using children()), its parent element (using parentElement()), its ‘neighbouring’ elements (using previousSibling() and nextSibling()) and much more. What we’re basically doing is traversing and altering the DOM (Document Object Model, or your HTML document).

Now here’s why I like and dislike JavaScript. It took me about fifteen minutes to get this example running… Fifteen!? Yes. Why? Because I spelled ‘innerHTML’ as ‘innerHtml’ and what does JavaScript do? You might say it gives us an error saying innerHtml does not exist. Wrong, what it actually does is create innerHtml on the ‘output’ variable (or more precisely the object it references). It doesn’t do anything with it, it just sits there. But in the meantime innerHTML remains empty, my page doesn’t show “Hello JavaScript!” and I’m not getting an error of any kind.
So with JavaScript you can actually alter already existing objects! How cool is that? Pretty cool, but it can lead to very subtle and hard to troubleshoot bugs, so be careful. That is also why you should always use the var keyword when creating variables. Failing to do so will work fine, but will actually create a property on your this object (the object, or context, you’re currently operating in).

And that’s actually all I’m going to tell you about basic JavaScript. The standard library is actually pretty difficult to work with and you’ll often deal with bugs like the one I just described. To top it off different browsers can behave differently using the same JavaScript code. Luckily (and also a bit unlucky) there are literally thousands of libraries and frameworks that do all the hard stuff for us. One of those libraries has become so popular that it has become the de facto standard when working with the DOM, I’m talking about jQuery.

Getting started with jQuery

There are two ways to get jQuery included in our page. One we have already seen. We get the jQuery files from jQuery.com, put them on our server (or during development our local machine) and get them in our page using the HTML script element. There are two versions you can get, the regular or the minimized version. The regular version is great for development as it is easier to debug. The minimized version has all unnecessary characters like spaces, meaningful variable names, white lines etc. removed from the file, making them practically unreadable, but making the file a little smaller in size making it to load a bit faster on our webpage. A lot of libraries have regular and minimized versions.

For this example we’re going to use the second method to get jQuery in our page though, which is through a CDN, or Content Delivery Network. A CDN is just some host providing you with popular files you might need, like jQuery. A possible benefit of using a CDN is that they might have servers across the globe, which means that if someone in America is using our website hosted in Europe they could still get jQuery from a server near them. Another possible benefit is that you don’t have to host the file yourself. So if you can, use a CDN.
Popular CDNs are Microsoft and Google, so let’s go with the Google CDN.
One word of caution though. Whenever your website requests a file from any CDN the host of that CDN may track the users of your page (they’re making a request after all). So while this is probably no problem for your personal website, it may be an issue for corporate environments where privacy and security are of bigger importance.

Let’s have a look at how our header looks with jQuery from a CDN.

<head>
    <meta charset="utf-8">
    <title>My first JavaScript!</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="MyJS.js"></script>
</head>

So you see, it actually looks the same, but we’re putting a link in the src attribute. Also notice that I put jQuery above MyJS because MyJS is going to need jQuery to run. Now let’s rewrite that sayHello function we had so it uses jQuery.

function sayHello() {
    var output = $('#output');
    output.text('Hello jQuery!');
}

Looks weird? $ is actually a perfectly valid function name in JavaScript and jQuery is utilizing it. $ is also called the jQuery function and alternatively you could’ve used jQuery(‘#output’). Now notice what we pass as a parameter to the jQuery function. It’s a CSS selector! Yes, you can get ANY element (or elements) on the page using CSS selectors. That’s great because we already know CSS. And when we have our output element we set the text (the part between the opening and the closing tags) to ‘Hello jQuery!’.

Now remember that I said we shouldn’t have JavaScript in our HTML? Well, we still have our onclick event in the button tag, so I guess I lied. JavaScript doesn’t really have a simple elegant solution to this problem. But jQuery does (they made it simple)! First of all let’s change our button tag so it doesn’t hard wire that onclick event.

<button id="btn">Press me!</button>

And next let’s take a look at our JavaScript.

$(document).ready(function () {
    $('#btn').on('click', sayHello);
});

function sayHello() {
    var output = jQuery('#output');
    output.text('Hello JavaScript!');
}

As you can see I’ve added a $(document).ready(function) call to our JavaScript page. That might look arcane, but it’s really simple actually. We call the jQuery function and pass it our document. We’re getting something back which obviously has a ready function that takes a function as parameter. This function, also called a callback function, is called when the document is ready (the HTML has loaded and is ready for traversal and manipulation). We then create an anonymous function to be called. It’s really the same as our sayHello function, except that we don’t give it a name. So in this anonymous function we get our button element and then call the on function on the result. With the on function we can hook up events to our elements. In this case we want the click event and we specify a function to be called when the click event fires (the button is clicked).
Here’s an alternative way of writing the above. I’m using a shorthand notation for $(document).ready by simply passing an (anonymous) function directly to the jQuery function.

$(function () {
    $('#btn').on('click', function () {
        $('#output').text('Hello jQuery!');
    });
});

Let that sink in. Study the syntax and compare the two examples. Take a look at how I rewrote the sayHello function to an anonymous function in particular, it may help understanding what’s going on. You may also want to try rewriting this using no anonymous functions.

There’s a whole lot to jQuery that I cannot show you in this blog, but the jQuery documentation is actually pretty good, so be sure to use it!

Now I’m going to show you another trick with which you can create beautiful pages using classes and CSS. First create a CSS file called MyStyle.css and add the following style to it:

.hovering {
    color: white;
    background-color: blue;
}

Now let’s create a single paragraph we want to light up once you hover your mouse over it. Don’t forget to link your stylesheet!

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <link rel="stylesheet" type="text/css" href="MyStyle.css">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <p id="p">Try hovering over me!<br>
        An extra line<br>
        so it's easier<br>
        to hover...</p>
    </body>
</html>

Nothing special there. Now for our JavaScript:

$(function () {
    $('#p').hover(function () {
        $(this).addClass('hovering');
    }, function () {
        $(this).removeClass('hovering');
    });
});

So we get out p element and then call the hover function which takes two functions as input. One function is called when your mouse enters the paragraph and the other function is called when your mouse leaves the paragraph (moving your icon over an element is called hovering). Now in this function we call the jQuery function and pass it this. The this keyword is a little difficult in JavaScript. This is the context in which you are currently operating, so this can refer to the window object (the ‘general context’), to an object in which you are currently operating, or in this case the HTML element on which the hover event is fired. So when we pass the p element (this) to the jQuery function we get a jQuery object on which we can call jQuery functions, such as text or addClass and removeClass. So we’re dynamically adding classes. But since our CSS applies a certain style to those classes we now get dynamic styling on our page!

jQuery UI

I want to show another quick example of how powerful JavaScript, and jQuery in particular, really is. For this we’re going to need jQuery UI. Another library that’s made by the jQuery people and uses jQuery, but adds functionality specifically for your UI (User Interface). Next to a JavaScript file the jQuery UI library makes use of a CSS file too. We can get both from the Google CDN we’ve used earlier. So here is the HTML. It looks large, but it’s quite simple.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first JavaScript!</title>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
        <script type="text/javascript" src="MyJS.js"></script>
    </head>
    <body>
        <div id="accordion">
            <h3>Page 1</h3>
            <div>
                <p>Some content...</p>
            </div>
            <h3>Page 2</h3>
            <div>
                <p>More content...</p>
            </div>
            <h3>Page 3</h3>
            <div>
                <p>Lots of content...</p>
            </div>
        </div>
        <br>
        <div id="tabs">
            <ul>
                <li><a href="#page1">Page 1</a></li>
                <li><a href="#page2">Page 2</a></li>
                <li><a href="#page3">Page 3</a></li>
            </ul>
            <div id="page1">
                <p>Some content...</p>
            </div>
            <div id="page2">
                <p>More content...</p>
            </div>
            <div id="page3">
                <p>Lots of content...</p>
            </div>
        </div>
    </body>
</html>

And now for some amazingly difficult JavaScript…

$(function () {
    $('#accordion').accordion();
    $('#tabs').tabs();
});

So check out the result with and without those two lines of JavaScript. You’ll be amazed! And that’s the power of JavaScript.

So in this post we’ve become familiar with JavaScript and jQuery. You can build amazing websites using JavaScript. There are literally thousands of JavaScript (and CSS) libraries and frameworks. Some, like jQuery, are pretty all-round, but some are really specific about doing one particular thing. In a later blog post I’ll point out some of the more popular ones.
Try to play around a bit with JavaScript. We’ve only scratched the surface. I haven’t even mentioned prototype, which is vital in fully understanding JavaScript. You can start getting your JavaScript skills up to date with a free ebook from SyncFusion: JavaScript Succinctly. Now as luck would have it there’s also a free jQuery ebook from SyncFusion: jQuery Succinctly. So I recommend creating a free account and downloading these sweet free resources (and no, I’m not affiliated with SyncFusion, I just like the Succinctly series).

JavaScript also adds functionality to get data from or send data to our server without having to refresh our entire page. This technology, called AJAX, is what I will talk about in my next blog post.

Stay tuned!

Web development #4: PHP in the back

Missed me? It’s been a while since I last blogged (about three months). I’ve been busy moving to my own house and getting up-to-speed at a new job. Lots of good stuff, but no blogging. Well today is the day I’m picking this up again and I’m just going to act like it’s three months ago and continue with the series.

  1. Web development #1: Internet and the World Wide Web
  2. Web development #2: Our first website using HTML
  3. Web development #3: Styling our page with CSS 3
  4. Web development #4: PHP in the back
  5. Web development #5: User input with HTML Forms
  6. Web development #6: Getting interactive with JavaScript
  7. Web development #7: Dynamic page updates with AJAX
  8. Web development #8: Where to go from here

So in the previous installments we’ve created a web page using HTML and CSS. We can actually build pretty nice websites using just those, but we still run into some trouble. What if we wanted to add content to our site? We’d have to edit our HTML each time. What if we wanted to display our website in multiple languages? What if we wanted users to be able to add content to the site (such as a blog)? In other words, we want our content to be dynamic. That’s all not possible using just HTML and CSS. We’re going to need a bit more. We’re going to need something creating our HTML on the back-end.

For this blog post I assume you are familiar with HTML and CSS, which you can read about in my previous blog posts, and that you’ve worked with some programming language before, preferably some C-based language such as C# or Java.

Introduction to PHP

So our back-end is just a server listening for requests. Whenever a request comes in we want to handle it and send a response (such as an HTML web page). We can handle these requests with a variety of tools and languages, but for this article I’m using PHP.

Why PHP? First of all it’s free. Second, it’s one of the most popular web languages that has been around for a good long while. It has a huge community and lots of documentation and tutorials. Third, virtually all web hosts, even the free ones, have support for PHP. Other languages, such as C#, are not always supported. Last, but not least, PHP is quite easy to learn because it can be pretty lightweight. Actually I’m simply going to write my PHP in Notepad++.

So PHP was created twenty years ago, in 1995, by Rasmus Lerdorf. Back then the PHP stood for Personal Home Page. They changed it to PHP: Hypertext Preprocessor, making it a recursive acronym (because the first P stands for PHP, of which the first P stands for PHP, of which the first P…). Clever, huh? Anyway, PHP is a scripting language, meaning it is interpreted rather than compiled. It’s also procedural, object oriented, weakly typed and it has C-based syntax. Enough talking, let’s code!

Setting up your environment

Unfortunately we can’t code just yet. Remember that your browser renders HTML and CSS. It can also run JavaScript (which I will discuss in another blog post), but it can’t execute PHP files. Usually your server handles PHP execution. Chances are you don’t have a web server laying around. Luckily you can configure your own PC to act as a web server.

To do this simply install web server software. You have a few choices, but I’m going for XAMPP. You can download XAMPP here and then simply install it (choose all default options, or change them if you know what you’re doing). When the installation is done XAMPP will ask you to start the XAMPP Control Panel. Start it and you’ll see a list of options. We’ll need Apache, so just start it. Now start your favourite browser and navigate to http://localhost. You should see a XAMPP page. Congratulations, you have just installed a (local) web server and you can now run PHP files!

To check if it really works create a new text file and name it “hello.php”. Inside the file place the following text:

<?php
    echo "Hello, PHP!";
?>

Now go to the installation folder of XAMPP (you can go there quickly by using the ‘Explorer’ button in the XAMPP Control Panel), find the htdocs folder and place your hello.php file there. Now, in your browser, navigate to http://localhost/hello.php. You should see the text “Hello, PHP!” And now that we’ve got the mandatory Hello world example out of the way let’s start writing some real PHP.

Learning the syntax

So let’s first look at some basic PHP syntax. Basically you’re going to write an HTML page with some PHP in it. The PHP is going to create some text representing more HTML. To indicate that you’re going to use PHP use the <?php open tag and to indicate that you’re done with PHP use the ?> closing tag. You’ve seen this in the example earlier.

The echo, or alternatively the print, statement outputs your code to HTML. In the above example it creates the HTML “Hello, PHP!”, which is just some text. But we could make that echo “<h1>Hello, PHP!</h1>” and we would get a header on our page.

So as I mentioned PHP is weakly, or loosely, typed. That doesn’t mean PHP doesn’t have types, it means a variable can change its type while the code executes. It also means you can add 3 to “3” and the result might be 6 or “33”, so a bit of caution is required when working with weakly typed languages (and in fact PHP always converts text to numeric when adding).
So what are the types in PHP? First we have the int for numerics without fractional components (so 1, 8, 42 and 986 are valid integers, 1.12 is not). Second there is float, or double, for numerics with fractional components. Then we’ve got the boolean or bool for a simple true or false. Next is the string for text (or an array of characters). Then we’ve got the array, or a 0-based indexed collection of stuff. There’s the object type, which encapsulates state and behaviour. And last, and actually pretty literal least, there’s NULL indicating the absence of any value.
Nothing special if you’ve worked with other languages before.

So how do we go about and use these types? Usually we’d want to store them in variables. So how do we declare variables? We actually don’t… Just assign a value to some variable and all of a sudden it’ll be there. It’s a kind of magic! And a variable always start with the $ sign. The typical variable declaration then looks like this:

$intVar = 42;
$floatVar = 3.142;
$boolVar = true;
$stringVar = "Some string"; // Double quotes.
$stringVarAltern = 'Alternative string'; // Single quotes.
$arrayVar = array('Pulp Fiction', 'Fight Club', 'Star Wars');

class person
{
    public $name = NULL;
    public $age = NULL;
}

$objectVar = new person();
$objectVar->name = 'Sander';
$objectVar->age = 27;

$nullVar = NULL;

Now aside from the class and objectVar that looks pretty straightforward right? But beware, the following is completely legal (PHP is weakly typed, remember?):

$stringVar = 'Some string';
$stringVar = 42;

Now that’s something you do want to look out for.
There’s something else about strings too. See how you can declare a string using single or double quotes? Well, the double quote strings are interpreted strings, meaning that any variable name you place in there will be evaluated before the string prints. If you ever need to concatenate string you can use the . operator.

$hello = 'Hello';
echo '$hello world!'; // Outputs $hello world!
echo "$hello world!"; // Outputs Hello world!
echo "$helloish world!"; // Error, $helloish is undefined!
echo "{$hello}ish world!"; // Outputs Helloish world!
echo 'Conc' . 'aten' . 'ate!'; // Outputs Concatenate!

Another thing that might surprise you is that PHP can treat anything as a boolean! Any non-default value will be true while all default values will be false, also called truthy and falsey. The next example uses an if/else statement to illustrate this. Try playing around with it.

if ("Hello") // Try 0, '', '0', 0.1, NULL and array().
{
    echo "Yep...";
}
else
{
    echo "Nope!";
}

So I’ve also shown you an if/else statement. Let’s look at some loops too.

$movies = array('Pulp Fiction', 'Fight Club', 'Star Wars');

for ($i = 0; $i < count($movies); $i++)
{
    echo "$movies[$i] <br>";
}

foreach ($movies as $movie)
{
    echo "$movie <br>";
}

Now there’s actually quite something going on there! First we initialize an array, which we’ve seen before. Now in the first for loop we start by declaring our counter variable $i, then we do a boolean test to check if we need to loop once more and finally we do an update (increment $i) after each iteration. In the boolean check we also use the count(array) function to check if we still have more elements in the array. Ideally you would perform this count outside of the statement so it only gets performed once.
The second loop is a bit more readable. I’m basically saying “for each element, which I will call $movie, in the array $movies do this…”. Now in the loop’s body you can freely use the current element using the $movie variable.
There are also do– and while loops, but I won’t discuss them here. For a programmer this shouldn’t be anything new!

Writing a page

Now let’s write an entire page. Usually you’d have a database, such as MySQL, running, but that’s a bit overkill for this post. So we’re going to read lines of text from a text file and show them on the page. You’ll see that you can update your page without actually modifying your HTML or PHP file.

So let’s first take the example with my favourite movies. We’re going to put our favourite movies in a text file and print them on our page. So create a new PHP file, call it movies.php and put it in the hpdocs folder (which is in your XAMPP folder). Now create a text file called movies.txt and put it in your htdocs folder with your PHP file. You can put some movie names in your text file. Each name goes on a seperate line (I’m calling it movies, but any value would suffice, of course).

For this example I’m going to use an unordered list. I haven’t shown this yet, but the HTML is as follows:

<ul> <!-- Unordered List -->
    <li>Some item</li> <!-- List item -->
    <li>Another item</li>
    <li>Third item</li>
    <li>etc...</li>
</ul>

You could also use an ordered list, in which case you’d use <ol> tags instead of <ul> tags.

So your PHP file could look like this (excluding the !DOCTYPE, html, header and body tags):

<h1>My favourite movies!</h1>
<p>
    <?php
        if (file_exists('movies.txt'))
        {
            echo '<ul>';
            $lines = file('movies.txt');
            foreach ($lines as $line)
            {
                echo "<li>$line</li>";
            }
            echo '</ul>';
        }
        else
        {
            echo 'No favourite movies found!';
        }
    ?>
</p>

So using the PHP function file_exists(string) we’re first checking if the movies.txt file exists at all. If it doesn’t we’ll simply show “No favourite movies found!”, but if it does we’re going to create an unordered list and read the files contents using the file(string) function. The file(string) function reads all lines of a file and puts them in an array. There’s more functions for file manipulation, but I won’t discuss them here. Next we’re looping through the lines we just got from the file. For each line we’re appending a list item element to our HTML. When all the lines are processed we close our unordered list.
And that’s our page! You can view it by navigating to http://localhost/movies.php. You can use some CSS to make it look a bit prettier and you’ll probably want to add some content too.

Now imagine you’d get that out of a database? Pretty neat, huh!

Functions

Now there are times when you have certain code that you want to reuse. Let’s say we want to create another unordered list based on another file. The same rules apply, except maybe we don’t have movies, but songs that we’d like to display. We can create function for this and have the filename passed in as a parameter. So let’s look at how we can put the code above in a function. At the top of your page put the following:

<?php
    function fileAsUnorderedList($fileName, $notFoundMessage)
    {
        if (file_exists($fileName))
        {
            echo "<ul>";
            $lines = file($fileName);
            foreach ($lines as $line)
            {
                 echo "<li>$line</li>";
            }
            echo "</ul>";
        }
        else
        {
            echo $notFoundMessage;
        }
    }
?>

As you can see we’ve defined a function that does the same as our previous code, except the filename and the message when the file is not found are passed in as parameters. Now how can we call this?

<h1>My favourite movies!</h1>
<p>
    <?php
        fileAsUnorderedList('movies.txt', 'No favourite movies found!');
    ?>
</p>
<h1>My favourite music!</h1>
<p>
    <?php
        fileAsUnorderedList('music.txt', 'No favourite music found!');
    ?>
</p>

And look at that! You can now add a second text file to your htdocs folder and your favourite music will be displayed the same as your movies. You still see almost identical code here, so we could change our function and make it do a bit more or we could create a second function that creates the header and paragraph for us.

And what if you wanted to use this function on other pages? Simply put the function in a seperate file and include the following line of code in the PHP file where you want to use the function.

<?php include("MyFunctions.php"); ?>

If you want to further organize your code, and you’ll want that, you’ll have to use objects and namespaces. You’ve already seen a little example of an object earlier and I’m leaving it at that. Be careful with putting functions directly in your files though. What if two files you want to include contain the same functions (or variables)!? You’d have a problem. Using objects and namespaces help toward preventing this.

So that was a very short introduction to PHP. Probably shorter than it deserves. PHP has lots of functions, libraries, third party tooling and a large and active community. If you want to learn more about PHP I suggest you start by Googling for tutorials or perhaps read a book about it. For now you’ve created your first website with dynamic content using a server-side language though! In my next post (which won’t take me another three months) we’ll look at sending data from our website to the server so we can use our page to add movies or music to the text files.

Stay tuned!