english

learn php

17. jquery & ajax get
10 minutes / 1867 words

seventeen

jquery, ajax & php

this is not a guide to using javascript. that might be a good thing to find if it's interesting to you or useful for your projects but it should get you started with the part that's functional for writing modern web apps with php -- using ajax.

the key to modern apps is not to have to go from page to page, submitting data and waiting for responses. that's possible because of ajax, using javascript to send and receive information in the background to change things on an existing page. you already have all the skills to deal with both the backend php and frontend html required with one exception, the ajax component.

there are many ways to integrate ajax into html but the easiest (and the only one i recommend) is using jquery, a javascript library that turns the html environment in the browser into something far more useful and directly-accessible with simple commands. from my perspective, jquery should have been integrated into javascript years ago and it shocks me that its command structure hasn't become the standard for all javascript.

the first step to using jquery is to load it in the html. you can either load it directly from a content delivery network (cdn) or download it and include it in the files for your app. we'll load it from the cdn because that's simpler. either provides the same results, though.

<script src="https://code.jquery.com/jquery-4.0.0.min.js" integrity="sha256-OaVG6prZf4v69dPg6PhVattBXkcOWQB62pdZ3ORyrao=" crossorigin="anonymous"></script>

you're already familiar with linking scripts this way. for scripts on other sites, integrity and crossorigin just ensure you're getting the right code without any malicious actors getting in the middle. with that in your head, it loads jquery and you can continue on to the next steps. you need a javascript file to put your client-side code in. we'll call that file parse.js because that's what it'll be doing but you can call it anything you like. like in our html/php examples, we will store our javascript files in js/.

<script src="js/parse.js"></script>

before we worry about the contents of parse.js, let's write parser.php, the php backend for our demonstration. all we want is for it to get one variable from the querystring that we'll call action and print different responses based on that variable's contents. this should be very easy for you to read at this point.

parser.php``

<?php

$action = trim($_GET["action"]);

$action == "one" && print_r("an elephant's trunk has about 150 thousand muscles.");
$action == "two" && print_r("anteaters can move their tongues at a rate of about 150 swipes per minute.");
$action == "three" && print_r("beavers naturally produce vanilla scent.");

now we need an html file that has some buttons to call those actions, a place for the returned strings to go and the javascript links we've already talked about.

index.htm

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=10.0" />
        <script src="https://code.jquery.com/jquery-4.0.0.min.js" integrity="sha256-OaVG6prZf4v69dPg6PhVattBXkcOWQB62pdZ3ORyrao=" crossorigin="anonymous"></script>
        <script src="js/parse.js"></script>
        <title>ajax demonstration</title>
        <base href="http://localhost" />
    </head>
    <body>
        <nav>
            <button action="one">first action</button>
            <button action="two">second action</button>
            <button action="three">third action</button>
        </nav>
        <main>
            <p id="message">you haven't clicked a button yet.</p>
        </main>
    </body>
</html>

this should look very familiar because it's almost exactly the structure from our template example. we've put http://localhost as the base url but you can use anything you like there to match your testing setup.

note that this page doesn't do anything. those buttons don't have anything in them other than a parameter that can be read. this is a custom parameter that will be read by the javascript. but buttons don't perform actions on their own. you can click them and that's all that happens. also note that the p tag has an id of message. that's where we're going to send the returned string and we'll do it by looking for that id. but that's the entire html file. there's nothing hidden behind the scenes.

all the activity happens in the javascript file...

parse.js

$(window).on("load", function () {
    $(document).on("click", "button", function () { 
        parse($(this).attr("action"));
    });
});

function parse(target) {
    $.get("php/parser.php?action=" + target, function (c) {
        c.trim().length > 0 && $("#message").html(c);
    });
}

javascript has a reputation for being both cumbersome to write and requiring extremely long code to get anything done. this is a skill issue. some people will say that using jquery is cheating but, as i said, jquery really should just be part of the standardized javascript language. i'm not alone in thinking this. both the largest social media network in the world, facebook, and the most popular blogging and site management platform, wordpress, use jquery.

if you're curious, this same task can be completed without jquery and it's only a few lines longer so that's not what's making it short. it's just not a very complex task.

if you've never written javascript before, this will probably still look somewhat familiar because javascript and php are both derived from the same coding structure. they use much of the same syntax and many of the same commands. given your familiarity with php, you already know quite a bit about writing javascript.

the first section is calling $(window). in php, $ refers to a variable. variables in javascript don't have that prefix. $ is actually calling jquery and passing it a search parameter for something in the browser to find. in this case, it is calling the window itself -- in other words, the browser's environment. on is a jquery function that fires when an event happens. it takes at least two parameters, the first being the event, the second being the action to take when that event happens.

the event is load. so, when the window loads, it performs the action. the action is a function with no parameters. in other words, when the page has finished loading, do everything inside the function.

the one line of code inside the function should look very familiar because it's in the same format. this time, we're using document, the page loaded in the browser. we're calling on again but with three parameters this time. the first parameter for on is always the event. it's self-explanatory -- click fires when the user clicks on something. the second parameter is the tag, class or id of the thing being clicked on inside document.

before we continue, we should be aware of a convention that works inside javascript and stylesheets for naming. anything with no prefix is a tag (a, body, p, button). anything with a . prefix is a class. anything with a # prefix is an id.

this parameter is button so it's a tag. search for any button inside document and, if it's clicked, do the third parameter, another function with no parameters. remember, jquery performs searches that match all elements given the parameters. so button matches every button, not just the first one. so this is when any button inside document is clicked.

this function just calls parse with a parameter. the parameter is $(this), referring to the element that's been clicked -- the button. we don't have to be specific because javascript is already aware which button it is and can pass that along. we're calling attr, which returns the value of any attribute (parameter) of the element (button). the parameter we're passing into attr is the attribute we want -- action, which we've set in the html.

the next block is the parse function. it's taking the parameter target, which we already know is the action from whichever button was clicked. as we already know, $ calls jquery. instead of (), though, we have ., which calls a jquery built-in function, in this case get.

get executes an ajax call to do a get request. there is also post to do the other type of request we've already discussed several times. get takes two parameters. the first is the link to get, which is just the php file we've already written with the action on the querystring. note that javascript uses + to join strings, not . like php. the second parameter is what to do when the get request is completed. it is a function and the parameter is the content of the response. in other words, it passes the page the server answers the get request with to the function.

that function just does two things. first, it checks to make sure there really is content by trimming any whitespace and seeing if it's longer than 0 characters. next, if that's the case, it looks for #message and sets it to be that content. if there's an error or the page returns nothing, the content will be empty and it will simply do nothing. whatever the contents of #message already were won't change.

remember, # is the prefix for an id. we have a p tag with id message in our html file so that's what will take the content, if there is any.

this might not immediately be clear the first time but, if it's not, go back and look at the php and html files again and try running the example on your own system. click the buttons and see what happens.

this is a very basic example of ajax but the important thing to take away is that it can send information to the server, get an answer back and do something with that answer. that information can be anything the user has done -- including typing or clicking. the answer can be anything from an empty string to entire documents, files or json. what it can do with it is anything javascript is capable of, which is reasonably only limited by the browser and attention-span of the user.

these ajax three-part actions are the backbone of the modern web, nearly everything you do on any web-based social media, for example, triggers ajax.

one last note. the file the user is seeing is a plain html file, not php. that means it hasn't had to be processed on the server. in other words, the server doesn't have to do any real work until the user takes an action that triggers something. so the page, given modern caching, loads almost instantaneously on any computer. all the actions take place in the background but the page itself doesn't have to reload, making everything feel fast and ensuring only the smallest amounts of information are passed back and forth instead of having to load whole new pages every time the user clicks on anything.

assignments

© avi sato. creative commons attribution-noncommercial-noderivatives.