Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
using POST in ajax in vanilla js

I am trying to send the post request to my PHP file but it is saying undefined index.

my js code -

document.getElementById("btn1").addEventListener('click', xh );

function xh(){
    xhr = new XMLHttpRequest();
    //xhr.open('GET', 'req.php?msg=hello bro', true);
    xhr.open('POST', 'req.php');
    xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
    
    xhr.onprogress = function () {
       // document.getElementById("loading").classList.remove("dis");
    }
    xhr.onload = function () {          
        console.log(this.responseText);
    }
    
        xhr.send("msg=hello");        
    }

my PHP code -

 <?php
        if(isset($_POST['msg'])){
            echo "set";
        }
        else{
            echo "not set";
        }
    ?>

I also tried the server request method but it didn't work

it is showing not set, and if I try to echo the $_POST['msg']; it says undefined index 'msg'

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of

xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');

you want to set the request header

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

Read more about XHR. The present approach it to use fetch() though.

fetch("req.php", {
  method: "POST",
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: "msg=hello"
}).then(response => response.text())
  .then(console.log)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!