In jQuery, the code is like this, and everything is happy as a lark:
$.post("bucket.php", { empty:"1" }, function(r) { ... });
The console in Firefox's dev tools says that "Form data" contains empty=1
, and the PHP file gets what it wants. I don't really understand that syntax (what { }
does and while empty
isn't in quotes), but it works.
Now I need to do the same thing in plain Javascript. Here is my code:
function bucketEmpty() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) { //no error
if (!isNaN(xhr.responseText)) { // return string is a number (expecting 0)
document.getElementsByClassName('bucketcount').innerHTML = xhr.responseText;
} else {
alert(xhr.responseText);
}
}
};
xhr.open('POST', 'bucket.php');
xhr.send(???what goes here???);
}
For the parameter of xhr.send() I have tried the following, none of which work:
'empty=1'
(according to this answer): The console says it's in "Request payload", not "Form data".{empty:"1"}
or{"empty":"1"}
: The console says "Request payload" contains "[object Object]".'{"empty":"1"}'
: The console says it's in a section called "JSON".
This would be easy with GET, but since it is changing something on the server, POST is more proper. What is the right syntax?
EDIT in response to Rayon and Atul Sharma:
Hmm, something else fundamental must be wrong. For diagnostics, I currently have this as the first line in bucket.php:
die("GET:\n".print_r($_POST,true)."\nPOST:\n".print_r($_POST,true));
Whether I use xhr.send(JSON.stringify({empty: '1'}))
(Atul Sharma's answer) or xhr.send('{"empty":"1"}')
(Rayon's comment), I get the result shown in this screenshot of the console and the output from the server:
And I decided to test GET - I changed the open command to this:
xhr.open('GET', 'bucket.php?empty=1');
The console says Query String contains empty: "1"
, but on the server $_GET
and $_POST
are still empty! Does vanilla JS just hate me? This works fine in jQuery.
EDIT #2: It's just me (or my server)!
After discovering that even my original simplest syntax works on jsfiddle (https://jsfiddle.net/3j42ztpf/), I wrote a WME test file pair for my own server. On both my local VM and my production VPS, it acts the same way - jQuery works but plain JS doesn't, regardless of whether the parameter is sent as text or JSON. There must be something different in the HTTP request between the JSFiddle test and the first link on my server test, but I can't spot it in devtools - the Request Payload is identical and the differences in the headers all seem logical. Try it yourself at: https://dev.kizunadb.com/testajax.html
The back-end file testajax.php only contains this:
<?php
if (empty($_POST['text'])) {
die('What do you want me to say?');
} else {
die ($_POST['text']);
}
So I really do have a more fundamental problem than just bad syntax. Can anyone spot the issue in their dev tools, or suggest something I should check on my server?