0

I want to send data from a select to a PHP using fetch. Then I will use this data in a SQL statement. I'm trying with this code (note: the option of the select are created dynamically with another script):

<div class="col-md-4">
 <label for="ImpiantoBatt" class="form-label">Impianto (proprietario e indirizzo)</label>
 <select id="ImpiantoBatt" name="ImpiantoBatt" class="form-select-ImpiantoBatt" required onchange="scelta('ImpiantoBatt', this)">
 <option value="">Seleziona</option> 
 </select>
</div>

and this script:

<script>
function scelta(ImpiantoBatt, element) {
 const data = {
                    ID: document.getElementById(ImpiantoBatt).value
              }
 fetch("php/batteries_search.php", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
                 "Content-Type": "application/json; charset=UTF-8"
               }
 })
   .then((data) => console.log(data))
</script>

on the console I got this: Response {type: 'basic', url: 'http://localhost/progetti/test/php/batteries_search.php', redirected: false, status: 200, ok: true, …}

Now, printing the data I have a correct value, for example: {ID: '7'} .

On the backend I'm trying to receive the data with

$plantID = ($_POST['data']);

but it says Warning: Undefined array key "data".

Where is the mistake? Thanks for your help

j08691
  • 204,283
  • 31
  • 260
  • 272
Andry
  • 323
  • 1
  • 2
  • 10
  • What is the value of the `response`? I would assume that it's not valid JSON and you need to debug why that is. – Rory McCrossan Oct 05 '22 at 13:29
  • That row was a typo. Removed. Now it says: Response {type: 'basic', url: 'http://localhost/progetti/test/php/batteries_search.php', redirected: false, status: 200, ok: true, …} but still the same error from the backend – Andry Oct 05 '22 at 13:38

1 Answers1

-1

POST variable is populated only when you send data using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type (check out the manual https://www.php.net/manual/en/reserved.variables.post.php). Try:

$data = json_decode(file_get_contents('php://input'), true);
  • 1
    "Or set "Content-Type" header to either application/x-www-form-urlencoded or multipart/form-data" — That will break it worse. JSON is JSON. Claiming it is a different kind of data will cause PHP to try to parse it as that format … and fail because it isn't. – Quentin Oct 05 '22 at 13:51