简体   繁体   中英

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?

You can add query strong to url

getRequest(
    'snippets/search.php?param='+param,  //URL for the PHP file.
    drawOutput,  //Handle successful request.
    drawError    //Handle error.
);

if you don't want to change url you can pass parama in send() method.

    ....
     req.send('param='+param);

Use jQuery's AJAX

Example code:

  $.post("edit.php",
  {
      phpcontent: jscontent,
      phpid: jsid,
  },
  function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
  });

And then you can use the PHP $_POST [ 'vars' ] .

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));

Update: adding styled text

You can of course add any kind of HTML and send it along in the JSON response, as long as you store it using the .html() jQuery function.

If you wanted to send some differently styled data, it would be better to build it client side, as long as its structure is known. For example we return

array(
    'status'  => 'success',
    'records' => array(
        0 => array( 'name' => 'John', 'surname' => 'Smith' , ... ),
        1 => array( 'name' => 'Jack', 'surname' => 'Evans' , ... ),
    )
)

and we treat it in Javascript with jQuery:

    function onSearchComplete(response) {
        if (response.status != 'success') {
            alert('Error: ' + response.message);
            return;
        }
        // Empty the grid
        $('#grid').empty();
        var table = $('<table>').addClass('data-table');
        response.records.forEach(function(record) {
            // This function will be executed for every record
            var row = $('<tr>').addClass('data-row');
            Object.keys(record).forEach(function(key) {
                // key is "name", value is "John"
                var cell = $('<td>').text(record[key]);
                // Note that above I use .text(), not .html().
                // It's faster, but if the server sends "<em>Italics</em>"
                // I'll not see "Italics" in italics - I'll see an ugly
                // "&lt;em&gt;Italics&lt;/em&gt;".
                // To interpret HTML tags, use .html().

                row.append(cell);
            });
            table.append(row);
        });
        // Finally put the table in place.
        $('#grid').append(table);
    }

You could of course assemble everything server side, and send along the HTML inside the JSON, as in the original answer, above. That works too. However, this way we get less traffic, and while code is a bit harder to write, it is easier to maintain. In general, when you write something once and then have to maintain it for ages, it's the way to go.

If the HTML becomes too complex, there are libraries for that too; you would be interested in Twig (PHP side) and Handlebars (Javascript side).

If you want to keep the same page but you need interaction with the server what are you looking for is AJAX , here is an example in pure javascript (no jQuery needed):

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4)
    {
        if(xhttp.status == 200) 
        {
            //Success, HTTP response code 200
            alert(xhttp.responseText);
        }
        else
        {
            //Failure, HTTP response code different from 200
            alert("Error while executing the request");
        }
    }
};
xhttp.open("GET", "/path/of/search.php?parameter=parameterValue", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send();

In this example the client is calling search.php on server at the path: /path/of/search.php , xhttp.readyState == 4 means that the request is done (so the operation is complete), xhttp.status contains the HTTP response code returned by the server, xhttp.responseText you will have everything that is printed from server (for example with echo ). You can easily manipulate the sent parameters by changing the string "/path/of/search.php?parameter=parameterValue" , for example: "/path/of/search.php?parameter="+variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM