Monday 12 March 2018

Your AJAX Starter Kit, jQuery edition (Part 1/2)

About a couple years back, I posted a useful little AJAX Starter Kit. This is late to the party, but it's time to revisit the AJAX Starter Kit... in jQuery.

I know, I know, I've pontificated a lot in the past about not resorting to jQuery for no good reason, and my stance hasn't changed much. And I still don't think learning jQuery without first knowing a healthy amount of JavaScript, is at all a good idea. That said, jQuery isn't exactly new to the game and it's an established enough part of the web development landscape that doing a jQuery edition of the AJAX Starter Kit is a sound idea. Besides, I don't have to like jQuery in order to fairly and objectively point out its usefulness.

Really, check it out here. (http://api.jquery.com/jquery.ajax/)

Let's get cracking...

First, of course, let's list down all the components required.

- A HTML document with a reference to a jQuery source file
- A back-end script for producing said content. (Example will be in PHP)
- JavaScript to combine the HTML with the back-end script.

Note that the required components are almost identical to those in the previous edition, except that the first component has a reference to a jQuery source file.

Here's the front-end code. Note the reference to the jQuery file in Google's API repository. If you don't want to depend on a connection to Google, just download the file and reference it locally. We're doing things the jQuery way now, so instead of an onload event in the body tag, we use the ready() method in the document object.

ajax_test_jquery.html
<!DOCTYPE html>
<html>
    <head>
        <title>AJAX Starter Kit, jQuery Edition</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready
            (
                function()
                {
                    ajax_frontend("Teochew Thunder");
                }
            );

            function ajax_frontend(strUser)
            {

            }
        </script>
    </head>

    <body>
        <div id="ajax_placeholder" style="border:1px solid #000000;width:200px;height:100px;">

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


All we'll be getting when we run the code in a browser, is this.

Now for the back-end...

This code is identical to what we used for the non-jQuery version.

ajax_backend.php
<?php
if (isset($_POST["user"]))
{
    echo  $_POST["user"] . " says ";
}
echo "Hello, world!";
?>


As with the last time, this is what we get from running the back end code in the browser. Honest, nothing different here!




Next

Some jQuery to bring these components together.

No comments:

Post a Comment