skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You need to set the Content-Type header. Here’s how you could do that:

     document.getElementById('saveButton').addEventListener('click', function() {
            var inst_a = new XMLHttpRequest();
            inst_a.open("POST", "check_name-indev02.php", true);
            
            // You need this line to fix you issue
            inst_a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            
            inst_a.onreadystatechange = function() {
                if (inst_a.readyState == 4 && inst_a.status == 200) {
                    console.log(inst_a.responseText);
                }
            };
            inst_a.send("inputname=dummy");
        });
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search