Background:
The following AJAX
code works successfully (ReactJS + JQuery frontend, PHP backend
).
const data = {request_type:"load_data", start:1, end:50};
$.ajax({
type: "POST",
url: "http://localhost/site/server.php",
data: data,
dataType: "json",
success: (JSobject) => {
this.setState({arr: JSobject.arr});
}
});
In Chrome Dev Tools server.php
's Headers show up as "Form Data
" like so:
At the PHP server backend, there's this line of code:
$request_type = $_POST["request_type"];
In an attempt to learn how to do Fetch (I've avoided it so far mostly because I had AJAX boilerplate that worked well), I've been playing around with trying to build a drop-in replacement for the above code.
I tried this:
const data = {request_type:"load_data", start:1, end:50};
fetch("http://localhost/site/server.php", {
method: "POST",
body: data
})
.then((JSobject) => {
this.setState({arr: JSobject.arr});
});
But I get this PHP error:
Notice: Undefined index: request_type in .....server.php
And in Chrome Dev Tools server.php
's Headers show up like so:
So, I tried changing the data to JSON.stringify(data) like so:
const data = {request_type:"load_data", start:1, end:50};
fetch("http://localhost/site/server.php", {
method: "POST",
body: JSON.stringify(data)
})
.then((JSobject) => {
this.setState({arr: JSobject.arr});
});
But I still get the exact same PHP error:
Notice: Undefined index: request_type in .....server.php
And in Chrome Dev Tools server.php
's Headers show up like so:
Out of general frustration (although it's pointless because I'd be still using JQuery), I thought I'd use JQuery's $.param()
, and that would surely work.
So I tried this:
const data = $.param({request_type:"load_data", start:1, end:50});
fetch("http://localhost/site/server.php", {
method: "POST",
body: data
})
.then((JSobject) => {
this.setState({arr: JSobject.arr});
});
Still get the same PHP error
Notice: Undefined index: request_type in .....server.php
And in Chrome Dev Tools server.php
's Headers show up like so:
My question: how do I modify the Fetch
code above so that it becomes a drop-in replacement for the AJAX
code up top.
I realize that the use of horizontal lines can be bothersome for some. You can give yourself permission to believe that it really helps a lot of us regular folks follow what's going on in the question.