This is taken directly from this W3Schools tutorial, but I modified the php file to use wordpress hooks and the js file to take in two variables, so that it can be used multiple times in a single page: https://www.w3schools.com/php/php_ajax_php.asp.
I have the following gethint.php file:
<?php
add_action("wp_ajax_GetHint", "GetHintFunction");
add_action("wp_ajax_nopriv_GetHint", "GetHintFunction");
// embed the javascript file that makes the AJAX request
//wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'ajaxtest.js', array( 'jquery' ) );
wp_enqueue_script( 'my-ajax-request', plugins_url( '/js/showHint.js', __FILE__ ), array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
function GetHintFunction(){
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
...
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
}
And the following showHint.js file:
function showHint(str, str2) {
if (str.length == 0) {
document.getElementById(str2).innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(str2).innerHTML = this.responseText;
}
};
xmlhttp.open("GET", MyAjax.ajaxurl + "?action=GetHint&q=" + str, true);
xmlhttp.send();
}
}
And here is the html page itself:
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value, 'txtHint1')">
</form>
<p>Suggestions: <span id="txtHint1"></span></p>
<p><b>Type another name in the input field below:</b></p>
<form>
Last name: <input type="text" onkeyup="showHint(this.value, 'txtHint2')">
</form>
<p>Suggestions: <span id="txtHint2"></span></p>
The problem is that my output has a zero at the end of the response. Here is how it looks: browser screenshot
I used chrome's developers tool and under XHR, I can see that the PHP response itself contains that zero at the end of the response. Even if I remove the second text box and the second variable from the js function, the issue continues, so the issue seems to be with the php file itself. Any thoughts?