Hello guys I just started learning php. So I was trying to make a post request from my javascript file to my php file by Fetch API
when I make the request in my console I'm getting this error Uncaught [in promise] SyntaxError: Unexpected token < in JSON at position 0
I don't understand why this error is happening. Please help me fix this problem.
JavaScript
// payload object
const data = {
first_name: "first name",
last_name: "last name"
}
// make the request
fetch["ajax-insert.php", {
method: "POST",
body: JSON.stringify[data],
headers: {
"Content-Type": "application/json; charset=UTF-8"
}
}]
.then[[response] => response.json[]]
.then[[data] => console.log[data]]
PHP
Udo E.
2,4712 gold badges18 silver badges28 bronze badges
asked Mar 11 at 17:44
1
You are getting this error: Uncaught [in promise] SyntaxError: Unexpected token < in JSON at position 0, because an HTML error response is being returned to the browser instead of json data.
In PHP, use file_get_contents["php://input"]
to get the string json and json_decode
to get a php
object as shown below. Note that what your javascript fetch call is expecting as returned data is only the json string
PHP
answered Mar 11 at 19:39
Udo E.Udo E.
2,4712 gold badges18 silver badges28 bronze badges
5
First your js file is missing one curly brace
method: "POST",
body: JSON.stringify[data],
headers: {
"Content-Type": "application/json; charset=UTF-8"
}
}]
.then[[response] => response.json[]]
.then[[data] => console.log[data]]
Also, in your php, you need send back a json something like