0

I have the following JavaScript code in the header of my page; note that I use POST:

function sendInput() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', 'http://.../somefile.php?someInput=123', true);
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4) {
          if (this.status >= 200 && this.status < 400) {
            alert('ready: ' + xmlhttp.responseText);
          }
        }
    };
    xmlhttp.send();
}

I call the function in body onload:

<body onload="sendInput();">

In the PHP file $_POST is empty. The value for someInput is found in $_GET.

Shouldn't an AJAX request done with POST arrive in $_POST?

2 Answers2

4

When you are using the url to form your variables is GET. In order to send via post you need to change your code like this:

    function sendInput() {
    var params = "someInput=123";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', 'http://.../lsomefile.php', true);
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4) {
          if (this.status >= 200 && this.status < 400) {
            alert('ready: ' + xmlhttp.responseText);
          }
        }
    };
    xmlhttp.send(params);
}
Virb
  • 1,639
  • 1
  • 16
  • 25
Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35
1

Yes, You couldn't get any values in $_POST. because no values posted by you. Please refer the below for posting data to particular URL Send POST data using XMLHttpRequest

Hari
  • 44
  • 9