2

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

<?php

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];

echo $first_name;
echo "<br />";
echo $last_name;

?>
1
  • from your question, you are sending json data via post to a php script and expecting a json response. If you want the required json response, you are not expected to have more than one echo statement. see my answer. Commented Mar 11, 2022 at 20:27

2 Answers 2

3

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

<?php

$json = file_get_contents("php://input"); // json string
echo $json;

// The following lines are only useful inside the php script
// $object = json_decode($json); // php object
// $first_name = $object->first_name;
// $last_name = $object->last_name;
// echo $first_name;
// echo "<br />";
// echo $last_name;

?>
Sign up to request clarification or add additional context in comments.

5 Comments

hello @Udo E. I did what you said but now in my console I'm getting this error Uncaught (in promise) SyntaxError: Unexpected token u in JSON at position 1 and in my php file I'm getting this warning Warning: Attempt to read property "first_name" on null in F:\Work\ajax_practice\ajax-insert.php
@FuhadHasan did you remove the commented lines in my answer. remove them and retry
@Udo E. after comenting those lines and echo $json my console error is gone and developer tool's network tab i can see the json string but in my ajax-insert.php file it's printing nothing.
@FuhadHasan if you are working with a database, your fetch would be expecting the result of the database query. You can get the elements of the json post as shown in the commented lines in my answer, use them to perform the database query and echo the result of the query in a json string like this echo '{"result": "' . $result . '"}';. This would be what your js fetch script would be expecting as response data. Take note of the order of the quotes. I couldn't post this in my answer as it isn't part of your question. You can post another question to get a proper answer.
@FuhadHasan your script isn't supposed to print anything on its own (that is meant for you to see). The echo statement in the php code is meant to be a response to the javascript Fetch call, and it is not meant to be displayed to you. In other words, the result of the echo statement would be seen only at the javascript client side and you would get an error if you simply run the php script on its own instead of requesting via javascript.
1

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

<?php
$content = trim(file_get_contents("php://input"));

//this content should be a json already
//{"first_name":"first name","last_name":"last name"}

//if want to access values
$_arr = json_decode($content, true);
$first_name = $_arr["first_name"];
$last_name = $_arr["last_name"];

//do what ever you want to do with first_name and last_name

//after you are done, be sure to send back a json
echo json_encode(['success'=>true]);
exit()

2 Comments

Hey @bcleo10 I tried your solution but it's not working I'm getting same error in my console and in my php file it says Warning: Undefined array key "first_name" in F:\Work\ajax_practice\ajax-insert.php and same for the last_name
Try: $first_name = $_arr->first_name; $last_name = $_arr->last_name; Because it returns an object and not an array. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.