Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!