Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
When using POST with Fetch API to send user input to php file / Session variable it returns undefined array key

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.

A print_r($_POST) output is :

Array ( ) 

A print_r($_SESSION) is :

Array ( [number2] => 
        [num1] => 
        [num2] => 
        [numbers] => Array ( ) 
)
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda