I’m trying to send user inputs with Fetch API to my php file using the POST method. I’ve tried this with XMLHttprequests and has no issue but now I want to start using Fetch API. When I use the GET method to send the variable to the $_SESSION array I have no problem and I can echo it out. When I use the POST method it would return always “Undefined array key” for the variables.
I’m new to this so any help is much appreciated.
PHP
<?php
// a sessions start
session_start();
// session variable
$number1 = $_POST['n1'];
$number2 = $_POST['n2'];
$_SESSION['numbers'] = $_POST;
echo $_SESSION['numbers']['n1'];
echo $_SESSION['numbers']['n2'];
?>
JS
document.getElementById('btn').addEventListener('click', addNumbers);
function addNumbers(){
var input1 = document.getElementById('one').value;
var input2 = document.getElementById('two').value;
fetch('serv.php',{
method:"POST",
body:'n1='+input1+'&n2='+input2,
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then((response) => response.text())
.then((data) => {
output.innerHTML += data;
})
}
I know that I should check if the Session variable is empty or isset but i removed it just for visibility purposes.