Monday 14 September 2015

Your AJAX Starter Kit (Part 1/2)

AJAX stands for Asynchronous JavaScript And XML, and is a technology that marries the front-end capabilities of JavaScript with the back-end code of other scripting languages such as PHP, C# and ASP.

For more on AJAX. follow this link. (https://en.wikipedia.org/wiki/Ajax_%28programming%29)

There's plenty you can do with AJAX. With it, you can make your web application perform like a desktop application, eliminating (or at least suppressing) many of the limitations of traditional web applications.

What I'd like to do here today is assemble an AJAX Starter Kit - basic components of AJAX that a web developer can use to make his very first AJAX-driven application. What we need is the following:

- A HTML placeholder for content.
- A back-end script for producing said content. (Example will be in PHP)
- JavaScript to combine the HTML with the back-end script.

Bear in mind that everything here is a bare-bones example. Your AJAX code would ideally be more complicated than this, otherwise you wouldn't really need AJAX, would you? These are just the building blocks. They're meant for you to expand on. There is actually a lot more to AJAX than what I'm about to show you. But as a start, well, you could do worse.

Here's the HTML.

ajax_test.html
<!DOCTYPE html>
<html>
    <head>
        <title>AJAX Starter Kit</title>
        <script>
            function ajax_frontend()
            {

            }
        </script>
    </head>
    <body onload="ajax_frontend();">
        <div id="ajax_placeholder" style="border:1px solid #000000;width:200px;height:100px;">

        </div>
    </body>
</html>


Here, I've set the function ajax_frontend() to fire off when the body loads. Feel free to change the name of the function, or set it to fire off on some other event such as a button click.

The div with an id of ajax_placeholder is exactly what it says - this div is a placeholder for your ajax-driven content. Again, feel free to change the id of this div.

This is what the front-end looks like when run on your browser.



And here's the back-end.

ajax_backend.php
<?php

if (isset($_POST["user"]))
{
    echo  $_POST["user"] . " says ";
}

echo "Hello, world!";
?>


This may seem overly simplistic. "Hello, world"? Really? But bear in mind that this is just an example. You could make your back-end script access a database for records or perform some calculations. The end result is, the text output of your code should appear in the ajax_placeholder div.

This is what your output should look like when you run it from the server.


Because there's nothing posted to the script, it says only "Hello World". Later, your AJAX code will send a value for your back-end script to use.

Easy so far?

Of course, this is just a front-end file and a back-end file. The whole point is to link them together. And that's the part that bears close examination.

Next

The AJAX call.


No comments:

Post a Comment