PHP Web Automation Integrating with JavaScript - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Web Automation Integrating with JavaScript - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, June 17, 2019

PHP Web Automation Integrating with JavaScript

PHP Web Automation


Integrating with JavaScript

Problem

You want part of your page to update with server-side data without reloading the whole page. For example, you want to populate a list with search results.

Solution

Use a JavaScript toolkit such as jQuery to wire up the client side of things so that a particular user action (such as clicking a button) fires off a request to the server. Write appropriate PHP code to generate a response containing the right data. Then, use your JavaScript toolkit to put the results in the page correctly.

Example  Basic HTML for JavaScript integration

            <!-- Load jQuery -->
            <script type="text/javascript"
                        src="//code.jquery.com/jquery-1.9.1.min.js"></script>
            <!-- Load our JavaScript -->
            <script type="text/javascript" src="search.js"></script>

            <!-- Some input elements -->
            <input type="text" id="q" />
            <input type="button" id="go" value="Search"/>
            <hr/>
            <!-- Where the output goes -->
            <div id="output"></div>

Example  JavaScript integration glue

            // When the page loads, run this code
            $(document).ready(function() {
                   // Call the search() function when the 'go' button is clicked
                   $("#go").click(search);
            });

            function search() {
                   // What's in the text box?
                   var q = $("#q").val();
                   // Send request to the server
                   // The first argument should be to wherever you save the search page
                   // The second argument sends a query string parameter
                   // The third argument is the function to run with the results
                   $.get('/search.php', { 'q': q }, showResults);
            }

            // Handle the results
            function showResults(data) {
                   var html = '';
                   // If we got some results...
                   if (data.length > 0) {
                        html = '<ul>';
                        // Build a list of them
                        for (var i in data) {
                               var escaped = $('<div/>').text(data[i]).html();
                               html += '<li>' + escaped + '</li>';
                        }
                        html += '</ul>';
                   } else {
                        html = 'No results.';
                   }
                   // Put the result HTML in the page
                   $("#output").html(html);
            }

Example  PHP to generate a response for JavaScript

            $results = array();
            $q = isset($_GET['q']) ? $_GET['q'] : '';

            // Connect to the database from Chapter 10
            $db = new PDO('sqlite:/tmp/zodiac.db');

            // Do the query
            $st = $db->prepare('SELECT symbol FROM zodiac WHERE planet LIKE ? ');
            $st->execute(array($q.'%'));

            // Build an array of results
            while ($row = $st->fetch()) {
                   $results[] = $row['symbol'];
            }

            if (count($results) == 0) {
                   $results[] = "No results";
            }

            // Splorp out all the anti-caching stuff
            header("Expires: 0");
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            header("Cache-Control: no-store, no-cache, must-revalidate");
            // Add some IE-specific options
            header("Cache-Control: post-check=0, pre-check=0", false);
            // For HTTP/1.0
            header("Pragma: no-cache");

            // The response is JSON
            header('Content-Type: application/json');

            // Output the JSON data
            print json_encode($results);

Discussion

The HTML is pretty minimal by design. All that’s there are a few elements and calls to load external scripts. Separating JavaScript from HTML is good development practice—similar to segregating your presentation logic and your business logic on the server side. 

The first <script/> tag loads jQuery from a  CDN. This is convenient so you don’t have to install it on your own server. Using // at the beginning of the URL is a handy trick to ensure it works well on both http and https pages.

The second should point to wherever you’ve put the code. That handful of JavaScript functions provides the bridge between the HTML elements and the server-side code. The first call to $(document).ready tells the web browser, “When the page is finished loading, run the Java‐Script code that tells the web browser, ‘When the go button is clicked, run the search() function.’”

A lot of JavaScript programming is event based—along the lines of setting up rules like “when such-and-such happens, run this function.” A web page studded with JavaScript does not have a strictly procedural flow from start to finish. 

Instead, it presents the user with lots of possibilities—clicking buttons, typing stuff in text boxes, clicking links, and so on. Your JavaScript code usually sets up various event handlers—functions that run in response to clicking, typing, and other events.

In the search() function uses jQuery’s $.get function to send a request back to the server, passing whatever’s in the text box as the q query string parameter. The other argument to $.get indicates that when the request arrives, it should be passed to the showResults() function.

The showResults() function, in turn, takes those results and builds an HTML list out of them. Once the list has been built up, it sets the content of the output <div/> to contain that HTML.

The familiar part of this triumvirate. It’s very similar to any “search the database for some stuff based on user input” PHP script, except for how it returns results. Instead of printing HTML, it uses the techniques to send back an uncacheable JSON response.

Writing applications that rely on JavaScript-based client-side activity requires a different programming paradigm than your typical PHP application. Instead of thinking about how to generate entire dynamic pages, you have to think about how to generate bits of dynamic data that client-side logic can display or manipulate in convenient ways.

 A toolkit such as jQuery gives you a robust platform on which to build such applications. It abstracts away many of the messy practicalities of JavaScript programming—cross browser incompatibilities, the guts of asynchronous I/O, and other housekeeping.


No comments:

Post a Comment

Post Top Ad