Reputation: 1195
I'm trying to get a fetch call in React to talk to a PHP script I'm running on MAMP..
For some reason it's giving me errors.. I'm not sure where to go from here..
This is the code I'm using in React:
getPHP = () => {
var formData = new FormData();
formData.append('content', 'test2');
fetch(`http://localhost:8888/phpBackend/demo.php`, {
method: 'POST',
headers: {
},
body: formData,
}).then(res => res.json())
.then(response => {
console.log('response:');
console.log(response);
});
}
onSubmit = (e) => {
e.preventDefault();
this.getPHP();
}
And my PHP Script:
<?php
$content = $_POST['content']
$response = array("success" => true, "message" => $content);
echo json_encode($response);
?>
I'm getting this error:
FileUploader.js:20 POST http://localhost:8888/phpBackend/demo.php 500 (Internal Server Error)
UserForm._this.getPHP @ FileUploader.js:20
UserForm._this.onSubmit @ FileUploader.js:44
callCallback @ react-dom.development.js:100
invokeGuardedCallbackDev @ react-dom.development.js:138
invokeGuardedCallback @ react-dom.development.js:187
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:201
executeDispatch @ react-dom.development.js:461
executeDispatchesInOrder @ react-dom.development.js:483
executeDispatchesAndRelease @ react-dom.development.js:581
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:592
forEachAccumulated @ react-dom.development.js:562
runEventsInBatch @ react-dom.development.js:723
runExtractedEventsInBatch @ react-dom.development.js:732
handleTopLevel @ react-dom.development.js:4476
batchedUpdates$1 @ react-dom.development.js:16659
batchedUpdates @ react-dom.development.js:2131
dispatchEvent @ react-dom.development.js:4555
interactiveUpdates$1 @ react-dom.development.js:16714
interactiveUpdates @ react-dom.development.js:2150
dispatchInteractiveEvent @ react-dom.development.js:4532
FileUploader.js:25 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at FileUploader.js:25
Originally there was a cross domain issue (cors) but that was fixed with an .htaccess file I added:
<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
RewriteEngine on
RewriteBase /
</IfModule>
Does anyone know why this is throwing errors?
Upvotes: 0
Views: 217
Reputation: 11
You have a typo in the php script on line 2. Your missing a semicolon on the end of the line.
<?php
$content = $_POST['content']; // there you missed the semicolon
$response = array("success" => true, "message" => $content);
echo json_encode($response);?>
Upvotes: 1