• Aucun résultat trouvé

Once you have verified that the search handler file is error free, we need to set up the JavaScript file that requests that page. In the mockup.html file, we simply wrote the JavaScript inside of a <script> tag. In the previous chapter, we used the wp_

register_script() and wp_enqueue_script() functions to include an external JavaScript file, and normally we would use them as we did previously. It's a matter of some debate, but in this situation, we are going to advise you not to add JavaScript that way. The difficulty here revolves around the fact that the JavaScript file needs to inherit some values from PHP, and the integration between JavaScript and PHP is sometimes tenuous. In particular, the JavaScript that we need to make the Ajax requests requires the URL of our plugin. That's easy enough for us to calculate when we include a file via PHP, but it's much more difficult if we were to reference an external file via a script tag and a src attribute.

It's not an ideal solution, but we're going to emulate the mockup here very closely because we intend to literally print the <script> tag and its contents into the document head. We wince a bit as we tell you to do this, but we winced even more at the alternative. First, let's copy the JavaScript from our mockup into a dedicated PHP file (yes, a PHP file). We are calling this file dynamic_javascript.php and we are storing it inside the includes directory because it is technically a PHP file that executes and is not a static JavaScript file. Add a little bit of PHP to the front of our JavaScript file. Here's what the js/live-search.js.php file looks like—again, most of this is simply pasted from mockup.html:

<?php

/*---A "mostly" static page. We do however, have to supply one of the functions with

a valid URL to where the search handler page lives.

---*/

// Create a div where we can dynamically send results

jQuery('#search-2').append('<div id="ajax_search_results_go_

here"></div>');

// Listen for changes in our search field (<input id="s" >) jQuery('#s').keyup(get_search_results);

}

/*---SYNOPSIS:

Query our external search page INPUT:

none; reads values from the id='s' text input (the search query) OUTPUT:

triggers the write_results_to_page() function, writes to console for logging.

---*/

function get_search_results() {

var search_query = jQuery('#s').val();

if(search_query != "" && search_query.length > 2 ) {

jQuery.get("<?php print $search_handler; ?>", { s:search_query }, write_results_to_page);

} else {

console.log('Search term empty or too short.');

} }

/*---SYNOPSIS:

Write the incoming data to the page.

INPUT:

data = the html to write to the page

status = an HTTP code to designate 200 OK or 404 Not Found xhr = object

OUTPUT:

Writes HTML data to the 'ajax_search_results_go_here' id.

---*/

function write_results_to_page(data,status, xhr) {

if (status == "error") {

var msg = "Sorry but there was an error: ";

console.error(msg + xhr.status + " " + xhr.statusText);

} else {

jQuery('#ajax_search_results_go_here').html(data);

} }

Make sense? We've just added a wee bit of PHP to the otherwise static file—the alternative would be to simply hardcode the path to the search handler and forgo all this drama. A hard-coded URL would work in a pinch, but it would fail in cases where the user changed his content directory in the wp-config.php file (which has been possible since WordPress 2.6), or in cases where WordPress was installed to a subdirectory, for example, http://yoursite.com/myblog/. For those reasons, we need to dynamically read the path to this search handler.

We now need to ensure that this JavaScript is added to the document head. Modify the head() function inside the includes/LiveSearch.php file:

/**

* head *

* Prints some JavaScript into the document head. We are printing directly

* to the document head because we need our JavaScript to contain a dynamic

* value that identifies the search handler script.

*

* @return none This does, however, create some HTML output */

public static function head() { if(self::_is_searchable_page()) {

$search_handler_url = plugins_url('ajax_search_results.

php',dirname( __FILE__) );

include('dynamic_javascript.php');

} }

We are almost done, but we also need to ensure that jQuery has been loaded so our custom JavaScript works correctly. Update your includes/LiveSearch.php script so that the initialize() function looks like the following:

/**

* initialize *

* The main function for this plugin, similar to __construct() */

public static function initialize() {

Test::min_php_version(self::min_php_version, self::plugin_name);

if(self::_is_searchable_page()) {

wp_enqueue_script('jquery'); // make sure jQuery is loaded!

Otherwise our JS will fail!

$src = plugins_url('css/live-search.css',dirname( __FILE__) );

wp_register_style('live-search', $src);

wp_enqueue_style('live-search');

} }

The only thing added was a reference to WordPress' wp_enqueue_script function; that will ensure that jQuery is loaded before we print our JavaScript to the document head.

Save the file and refresh your homepage in a browser. View the source code and verify that jQuery and our custom JavaScript are being included. Make sure you test this in Firefox with the FireBug plugin enabled. That will alert you to JavaScript errors.

Finally, try typing in a search term. If all goes correctly, the static text that you have sitting on the ajax_search_results.php page should be inserted into the area below your search form. If you encounter any errors, track down the problematic areas using Firebug.

Was this an ideal solution? No. However, by including the dynamic_javascript.

php file, we were more easily able to ensure that the JavaScript had the correct value passed to it from PHP. Some readers may prefer to try this the other way around by using the wp_enqueue_script() function to include the JavaScript, but as we mentioned, it's more difficult to pass a PHP value to an external JavaScript file. If you want to try that method, read the next section for some ideas first. You will see that you can gain access to WordPress' functions and constants when you include the wp-config.php file. That, along with the use of PHP's header function could be your ticket to dynamically generating an external JavaScript file for inclusion via the wp_enqueue_script() function, but we're getting ahead of ourselves.

The only task remaining for us is to actually do the dynamic searches in the ajax_search_results.php page. Let's finish this thing.