I was trying to pass a Javascript variable to PHP through POST xmlhttprequest but even a text literal is not working.
I checked the answered question passing a javascript variable to PHP with xmlhttprequest but it did not work in my case. Below is my code
HTML/Script
<!DOCTYPE html> <html lang="en">
<button type="button" id="saveButton">Save Button</button>
<script> document.getElementById('saveButton').addEventListener('click', function() {
var inst_a = new XMLHttpRequest(); inst_a.open("POST", "check_name-indev02.php");
inst_a.send("inputname=dummy");
inst_a.onreadystatechange = function() {
if (inst_a.readyState == 4 && inst_a.status == 200)
{console.log(inst_a.responseText);}
}
});
PHP
<?php if (isset($_POST['inputname']))
{echo "set";} else {echo "not set";} ?>
I am not sure what I am doing wrong. The console always returns "not set" which means the constant "dummy" never reached the PHP. The actual page does a lot of other things including Jquery calls but only this part isn’t working. So I am including only the identified issue.
2
Answers
Because you were not properly reporting your
POST
data type, so$_POST
was not filled.Setting HTTP header
Content-Type: application/x-www-form-urlencoded
can tell PHP to parse yourPOST
ed body.You need to set the Content-Type header. Here’s how you could do that:
The setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); line is crucial because it tells the server that you’re sending form data (similar to what a regular HTML form does).