I'm having a problem trying to send information from JS to a php API
I am using the localstorage which is the one that I am going to send to the php file, in the html I press send and activate the following
console.log(JSON.stringify(localStorage));
if (val) {
confirmacion = confirm("Revisa tu infomacion que si intentas regresar, se borrara! :c");
//gen id y realizar post a php
idGen();
toPHP();
}
//console.log(localStorage);
function toPHP(){
fetch('base.php',{
method: 'POST',
body: JSON.stringify(localStorage)
})
.then(res => res.json())
.then(data => {
console.log(data);
})
}
function idGen(){
let id = '';
for(let i =0 ; i < 5 ; i++){
id += Math.floor(Math.random()*9);
}
localStorage.setItem("id",id);
}
And my php file is the following:
<?php
header("Access-Control-Allow-Origin:*");
$db = new mysqli('localhost','root','','pruebal');
$db->query("SET NAMES utf8");
$id = $_POST['id'];
$name = $_POST['name'];
$lastName = $_POST['lastName'];
$grade = $_POST['grade'];
$group = $_POST['group'];
$age = $_POST['age'];
$mail = $_POST['mail'];
$sql = "INSERT INTO general VALUES(
'{$id}','{$name}','{$lastName}',
'{$grade}','{$group}','{$age}','{$mail}');";
$save = $db->query($sql);
if($save){
echo json_encode('Exito!');
}else{
echo json_encode('Error!');
}
?>
The error I get is this:
Just in case, I'm working on this in the htdocs folder and with xampp already with apache and mysql active, and I run the application with Live Server in VSCode, I started to investigate, but I don't receive anything compelling or maybe I don't understand the everything, but I already tried in a thousand ways
Note that JSON means an element that you bind to
{"clave" : "valor"}
or an array of values["valor1", "valor2", "valorN"]
.By doing this:
Or this:
You would not be producing valid JSON to consume on the client.
Try like this:
Thus, you will have a valid JSON that will be, depending on the case:
EITHER:
This would be the most logical , that is, a text associated with a key called
msg
, and to display it where you receive the response you would do something like this:laRespuesta.msg
, wherelaRespuesta
represents your JSON.You can also do something like this (although it is not recommended for this case):
The result will also be a valid JSON with this:
Or with this:
And to consume it:
laRespuesta[0]
, wherelaRespuesta
would represent your JSON. But this is less logical , because we are not talking about a collection of things, but about a simple answer. If it were a collection or a list it would make sense, because you could for example get each element inside a loop.