GET request works:

var xhr = new XMLHttpRequest; xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.querySelector('.response').innerHTML = this.responseText; } } xhr.open("GET", "search.php?q="+val, true); xhr.send(); 

PHP (GET):

  header("Content-type: text/plain; charset=windows-1251"); if(ISSET($_GET)) { $val = $_GET['q']; echo $val; } else { echo 'Not GET variables'; } 

POST:

 var xhr = new XMLHttpRequest; xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.querySelector('.response').innerHTML = this.responseText; } } xhr.open("POST", "search.php", true); xhr.send(val); 

PHP:

 header("Content-type: text/plain; charset=windows-1251"); if(ISSET($_POST)) { $val = $_POST['val']; echo $val; } else { echo 'Not POST variables'; } 

JS full:

 var val; var inp = document.querySelector("#query-input"); inp.onkeyup = function () { val = inp.value; if (val.length != 0) { var xhr = new XMLHttpRequest; xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.querySelector('.response').innerHTML = this.responseText; } } xhr.open("POST", "search.php", true); xhr.send(val); } } 

POST request does not work. There is no answer at all. Those. there is a request, but the server is not responding, although the variable val is defined. How to make a request?

    1 answer 1

    The first. Use empty() instead of isset() . isset() checks for the existence of a variable (the $_GET and $_POST variables always exist), and empty() whether the variable exists and is empty (there are many nuances, check them in the documentation ). In your PHP code, the else will never work.

    The second. In your example with a POST request for JavaScript, the variable val contains a string in the wrong format. In order for PHP to be able to use it, this variable must be a string that has the format foo=bar ( foo is the name of the field of the POST request, bar is the value of the field). That is, in your case, the variable val should be a string val=example so that it can be accessed in PHP as $_POST['val'] . That is, the fourth line of your last code block should be replaced with this:

     val = 'val=' + encodeURIComponent(inp.value); 

    I advise you to read the article about XHR , which explains in detail this point.

    Third. In PHP, use lowercase functions. Not ISSET() , but isset() .

    Fourth. Enable the display of errors in PHP. Register it at the beginning of the very first file called:

     error_reporting(E_ALL); ini_set('display_errors', 1); 

    Because PHP could not find the $_POST['val'] variable in your system, it threw the error and stopped working, which is why your script did not output any text to you.

    • Thanks for the detailed explanation! - user7103883