XMLHttprequest sends an empty message

I use the following code to send a request:

var ajaxHandler = new XMLHttpRequest();

ajaxHandler.onreadystatechange = function()
{
   if(ajaxHandler.readyState == 4)
   {
      console.log(ajaxHandler.responseText);
   }
}

ajaxHandler.open("POST", "filterCards", true);
ajaxHandler.send("category="+category+"&tag="+tag);

On the PHP side, I have the following:

var_dump($_POST);

However, although both category and tag variables have values, the console registers an empty array. What am I doing wrong with the message?

+3
source share
2 answers

Add setRequestHeaderbefore submitting:

ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxHandler.send("category="+category+"&tag="+tag);

Replace:

   if(ajaxHandler.readyState == 4)
   {
      console.log(ajaxHandler.responseText);
   }

with

   if(ajaxHandler.readyState == 4 && ajaxHandler.status==200)
   {
      console.log(ajaxHandler.responseText);
   }

Hope this helps.

+5
source

Web-nomad's answer is correct, but if you still get an empty array, remember if you hide file extensions in your server configuration. If so, the request to "file.extension" will be redirected to "file" and the POST data will be lost.

, . , , URL, - , URL .

0

All Articles