when I try to fetch a formData with POST from JS to PHP, I obtain an empty $_POST array(), despite of Status Code is 200 OK. Can you help me?
function select_collection()
{
const tendina=document.querySelectorAll(".tendina");
for(all of tendina)
{
all.addEventListener('change', aggiungi);
}
}
function aggiungi(event){
const tendina=event.target;
const val=tendina.options[tendina.selectedIndex].value;
const row_box= tendina.parentNode.parentNode;
const child=row_box.childNodes;
const url_image=child[0].childNodes[0].currentSrc;
const id_google=child[1].childNodes[0].textContent.slice(11,);
const titolo= child[1].childNodes[1].textContent.slice(8,);
const autore= child[1].childNodes[2].textContent.slice(8,);
const editore=child[1].childNodes[3].textContent.slice(9,);
const pagine=child[1].childNodes[4].textContent.slice(8,);
var formData = new FormData();
formData.append('titolo_racc', val);
formData.append('id_google', id_google);
formData.append('titolo', titolo);
formData.append('autore', autore);
formData.append('editore', editore);
formData.append('pagine', pagine);
fetch('http://localhost/progetto/inserisci_contenuto.php',{
method: "POST",
body: formData
}).then(onResponse).then(onText);
.tendina it's the class of a drop-down menù (select, option), title, author, publisher and pages refers to a book volume infos. I want to send this info to a PHP page.
$conn=new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
die ("Connection failed " .$conn->connect_error);
}
if(isset($_POST["titolo_racc"]) && isset($_POST["id_google"] && isset($_POST["titolo"] && isset($_POST["autore"] && isset($_POST["editore"] && isset($_POST["pagine"]))
{
print_r($_POST); // array ()
print_r($_POST["titolo"]; //Undefined index:
}
Get rid of:
headers: new Headers({
"Content-Type": "application/json;"}),
it's incorrect, since you're sending multipart/form-data
format. You need to allow fetch()
to provide this header by itself, since it needs to include the separator string, which is generated randomly internally.
I find that the problem is in the session_start(), that I use to recognize the user_id. In fact, if I try to use $_SESSION["user"], i don't know why, it doesn't work.
If I don't write the session_start(), all the print_r and echo work very well, also with the fetched values.
The strange thing is that I use the session method in every others php pages of my website.