1

I am working on something and I have a very weird problem. I submit an AJAX request like following:

x = new XMLHttpRequest();
x.open('POST', url, true);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onload = function(){
    console.log(x.responseText);
};
x.send(data);

The problem is, when I submit the request, the PHP doesn't receive the POST values. The data variable looks like following:

Object { wordtype: "noun", word: "computer" }

And the PHP like following:

if(!isset($_POST['wordtype']) || !isset($_POST['word'])){
    echo "error 1";
    exit;
} else {
    $wordlist = json_decode(file_get_contents("words.json"), true);
    $wordlist[$_POST['word']] = $_POST['wordtype'];
    file_put_contents("words.json", json_encode($wordlist));
    echo "success";
}

The value of x.responseText is always error 1;

Thank You
Jacques Marais

Jacques Marais
  • 2,666
  • 14
  • 33
  • Do you mean to use `onreadystatechange` instead of `onload`? You should also be using an `application/json` Content-Type and using `JSON.stringify` on the object that you are sending. –  Oct 15 '15 at 15:32
  • @RalphWiggum http://stackoverflow.com/a/14946525/5305938 – Jacques Marais Oct 15 '15 at 15:35

1 Answers1

1

This example works:

var http = new XMLHttpRequest();
var url = "ajax.php";
var params = "wordtype=noun&word=computer";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
fico7489
  • 7,931
  • 7
  • 55
  • 89
  • Thank you so much. I think the problem was that I were using an object as data to send instead of a parameter string, and I sent the wrong headers. – Jacques Marais Oct 15 '15 at 15:40