I'm using reactjs
and PHP
and trying to POST
some data using fetch API
. The data is posted successfully but the format of data is weird on server-side, that I'm not able to use it.
Here is part of my code:
Javascript
var url = "http://cyg.com/router.php";
var data = {
service: 'Grade',
programme: this.state.programme,
enrolment: this.state.enrolment
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
})
.then(
res => res.json()
)
.then(
(result) => {
console.log(result);
//code to handle result here...
},
(error) => {
console.log(error);
//code to handle error here...
}
);
PHP
<?php
print_r($_POST); // here just to verify posted data. Remove later.
$service = $_POST['service'];
$programme = $_POST['programme'];
$enrolment = $_POST['enrolment'];
//some to code to process request....
?>
On posting data, it gives error that says undefined indexes service
, programme
and enrolment
.
On Inspecting the XHR POST
request in console
of the browser I got following Params and Response of the request.
You can see in Response (2nd Image), the value of $_POST
is in the format:
Array
(
[{"service":"Grade","programme":"BCA","enrolment":"147996460"}] =>
)
I'm not able to figure out the reason of the problem. However, if I change the Javascript in the following way, everything works fine.
Modified JavaScript
var url = "http://cyg.com/router.php";
/*var data = {
service: 'Grade',
programme: this.state.programme,
enrolment: this.state.enrolment
};*/
var data = "service=Grade&programme="+this.state.programme+"&enrolment="+this.state.enrolment;
fetch(url, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
})
.then(
res => res.json()
)
.then(
(result) => {
console.log(result);
//code to handle result here...
},
(error) => {
console.log(error);
//code to handle error here...
}
);
On changing JavaScript, I observe a change in the format of request params too, It is as follow:-
Thank You!!