user1375691 user1375691 - 1 month ago 6
PHP Question

Pass current HTML textbox value from JavaScript to PHP without reloading the page or writing to the URL

This file is index.php. It has a text box where someone can enter characters. Onkeyup, a JavaScript function is triggered, which calls search.php:

<input type="text" id="search" placeholder="filter items" onkeyup="return searchFunc()">

<script>
function searchFunc() {
var param = document.getElementById("search").value; //Current value in text box.
getRequest(
'snippets/search.php', //URL for the PHP file.
drawOutput, //Handle successful request.
drawError //Handle error.
);
return false;
}

//Handles drawing an error message.
function drawError() {
var container = document.getElementById('grid');
container.innerHTML = 'Oops, there was an error!';
}

//Handles the response, adds the HTML.
function drawOutput(responseText) {
var container = document.getElementById('grid');
container.innerHTML = responseText;
}
//Helper function for cross-browser request object.
function getRequest(url, success, error) {
var req = false;
try{

//Most browsers.
req = new XMLHttpRequest();
} catch (e){

//Internet Explorer.
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {

//Older versions.
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}

if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}

req.open("GET", url, true);
req.setRequestHeader("Cache-Control", "no-cache"); //Prevents browser from caching the last response (This line and the next two.)
req.setRequestHeader("Pragma", "no-cache");
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.send(null);
return req;
}
</script>

<div id="grid">
Type something into the search field!


The above code works perfectly, and was composed mostly from me searching on this forum for hours.

Next, let's move on to search.php. The point of this file (eventually) is to search a MySQL database for rows with 'title' that match what the user has began entering into the search box, and further refining the results after each keypress. But for testing purposes, All I want to display is the current value in the search box.

<?php
echo $_GET['param'];
?>


When I begin typing into the search box, I get:
"Notice: Undefined index: param in C:\xampp\htdocs\testsite\snippets\search.php on line 22"
. I am definitely using $_GET wrong. I've seen countless threads that indicate you can achieve this by appending your parameter onto the URL like "?value="+param, and referencing it from PHP, but I'm not writing to the URL - the URL doesn't change at all through this entire process. Can someone point me in the right direction?

Answer

Pursuant to my comment, this is how you could do this using jQuery and PHP:

<input type="text" id="search" placeholder="filter items" />
<div id="grid"></div>

<script>
    // Store response into grid.
    function onSearchComplete(response) {
        $('#grid').html(response.html);
    }

    function onKeyUpSearch() {
        $.post(
            'search.php',
            {
                ts   : Date.now(), // Be very very sure we're not caching
                text : $('#search').val()
            }
        ).done(onSearchComplete);
    }

    $(function() {
        // Main
        $('#search').on('keyup', onKeyUpSearch);
    });
</script>

PHP side:

$text = $_POST['text'];


$response = array(
    'status' => 'success', // This may come handy later on.
    'html'   => "<strong>OK! You typed {$text}.</strong>",
);
header('Content-Type: application/json;charset=utf-8');
die(json_encode($response));
Comments