phpxmlhttprequest

Not able to pass even a text constant to PHP using XMLHttpRequest


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.


Solution

  • Because you were not properly reporting your POST data type, so $_POST was not filled.

    var inst_a = new XMLHttpRequest();
    inst_a.open("POST", "check_name-indev02.php");
    
    // Need this line
    inst_a.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    
    inst_a.send("inputname=dummy");
    

    Setting HTTP header Content-Type: application/x-www-form-urlencoded can tell PHP to parse your POSTed body.