Hola chicos, acabo de empezar a aprender php. Así que estaba tratando de hacer una solicitud posterior desde mi archivo javascript a mi archivo php mediante Fetch API cuando realizo la solicitud en mi consola. Recibo este error No Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I no entiendo por qué está ocurriendo este error. Por favor ayúdenme a solucionar este problema.
// 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 $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; echo $first_name; echo "<br />"; echo $last_name; ?>Primero, a su archivo js le falta una llave
method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json; charset=UTF-8" } }) .then((response) => response.json()) .then((data) => console.log(data))Además, en su php, necesita enviar un json algo así como
<?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()Está recibiendo este error: Uncaught (en promesa) SyntaxError: token inesperado < en JSON en la posición 0 , porque se devuelve una respuesta de error HTML al navegador en lugar de datos json.
En PHP, use file_get_contents("php://input") para obtener la cadena json y json_decode para obtener un objeto php como se muestra a continuación. Tenga en cuenta que lo que espera su llamada de recuperación de javascript como datos devueltos es solo la cadena json
<?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; ?>