MedMatrix MedMatrix - 7 months ago 19
Javascript Question

Retrieve input value with server-side script for autocomplete()

When I try to implement auto-complete using the code below :

$('#keyword').autocomplete({
source : '/Dev/pages/search.php',
minLength : 3,
type : 'POST',
select: function( event, ui )
{
$(this).data("autocomplete").menu.element.addClass("yellow");
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
console.log(item);
return $( "<li>" )
.append( "<a>" + add3Dots(item.name,20) + "</a>" )
.appendTo( ul );
};





if (isset($_POST["term"])){

$term = trim($_GET['term']);

$parts = explode(' ', $term);
$p = count($parts);

$a_json = array();
$a_json_row = array();

$search = connexion::bdd_test();
$requete = "SELECT name from BDD_TEST.companies";

for($i = 0; $i < $p; $i++) {
$requete .= ' WHERE name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}

$result = $search->query($requete);
while($donnees = $result->fetch(PDO::FETCH_ASSOC)) {
$a_json_row["name"] = $data['name'];
array_push($a_json, $a_json_row);
}

}
else
{
$a_json['call']=false;
$a_json['message']="Problem to collect word.";
}

$json = json_encode($a_json);
print_r($json);


When I test, if condition is not satisfied and I get the message directly from else " Problem to collect word . "
It means that $_POST["term"] is not defined.

How can I retrieve the input value ?

Answer

To be sure that values have been send, you can see what headers the browser sent to the web server with PHP for testing purposes.

This is possible using the apache_request_headers() function but it only works if PHP is run on Apache as a module.

  • How using apache_request_headers() :

If PHP is run on Apache as a module then the headers the browser send can be retrieved using the apache_request_headers() function. The following example code uses print_r to output the value from this function call:

print_r(apache_request_headers());

The output from the above using an example request from Google Chrome would output something similar to the following:

Array
(
  [Host] => www.testing.local
  [Connection] => keep-alive
  [User-Agent] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
  [Cache-Control] => max-age=0
  [Accept] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
  [Accept-Encoding] => gzip,deflate,sdch
  [Accept-Language] => en-US,en;q=0.8
  [Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
)
  • Alternative when PHP is run as a CGI :

If PHP is not being run as a module on Apache, the browser headers should be stored in the $SERVER array with the key being the request header name converted to upper case, hypens replaced with underscores, and prefixed with HTTP

The same request above showing the relevent lines from $_SERVER are as follows:

[HTTP_HOST] => www.testing.local
[HTTP_CONNECTION] => keep-alive
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_ACCEPT] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3

The alternative method is create our own function if the apache_request_headers() function does not exist, which extracts just the values from $_SERVER and converts the key names to the same style as apache_request_headers(). This works like so:

if(!function_exists('apache_request_headers')) {
    function apache_request_headers() {
        $headers = array();
        foreach($_SERVER as $key => $value) {
            if(substr($key, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

The new function is only declare if the function with that name does not already exist. The end result is that whether or not the internal PHP function exists, you will be able to call a function with this name in your code.

A loop is done though the $SERVER array and any whose key starts with HTTP is added to the array, and the key is translated via a series of function calls to be in the same format as returned by apache_request_headers().

  • View HTTP headers in Google Chrome

Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.

Press F12 on windows or ⌥⌘I on a mac to bring up the Chrome developer tools.

enter image description here

  • Try to retrieve value(s) without knowing HTTP methods

You can detect which request type was used (GET, POST, PUT or DELETE) in PHP by using

$_SERVER['REQUEST_METHOD']

For more details please see the documentation for the $_SERVER variable.

Or you can retrieve value(s) using $_REQUEST['you_variable'].

Note $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the elements in $_REQUEST, nor vice versa.

Comments