Skip to content
Advertisement

fetch send formdata and recieve it from php

Hello srry for bad english, i’m trying to insert some formdata to my sql database with fetch request, the row was added and the id counts +1, but theres no extra data added to the columns “nomtar”,”destar”,etc

JS function on submit form:

function enviarDatos(e){
    e.preventDefault();
    var nomtar = document.getElementById('nomtar').value;
    var destar = document.getElementById('destar').value;
    var usu2tar = document.getElementById('usu2tar').value;
    var fectar = document.getElementById('fectar').value;
    formData = new FormData();
    formData.append('nomtar',nomtar);
    formData.append('destar',destar);
    formData.append('usu2tar',usu2tar);
    formData.append('fectar',fectar);
    fetch('servicios/agregar.php',{
      method: 'POST',
      headers: {
                  'Content-Type': 'application/json'
              },
      body: JSON.stringify(formData)
    }).then(response => {
      if(response.ok){
        console.log("datos enviados");
      }
      else{
        console.log("datos no enviados");
      }
    }).catch((error) => {
      console.log(error)
      });
  }

agregar.php FILE:

    <?php
  session_start();
  include('conexion.php');
  $data = json_decode(file_get_contents('php://input'), true);

  $nomtar=$data['nomtar'];
  $destar=$data['destar'];
  $fectar=date('Y-m-d',strtotime($data['fectar']));
  $usu1tar=$_SESSION['idusu'];
  $usu2tar=$data['usu2tar'];
  $query="select idusu from usuario where nombre='$usu2tar'";
  $result1=mysqli_query($con,$query);
  if($result1){
    while($row=mysqli_fetch_array($result1)){

        $idusu=$row['idusu'];

    }
  }


  $sql="INSERT INTO tarea(usu1tar,usu2tar,nomtar,destar,fectar,esttar) VALUES('$usu1tar','$idusu','$nomtar','$destar','$fectar',1)";
  $result2=mysqli_query($con,$sql) or die(mysqli_error($con));


  mysqli_close($con);
?>

Advertisement

Answer

There’s no need to convert your form data to JSON. Fetch understands FormData directly.

Change this line

body: JSON.stringify(formData)

to this:

  body: formData

Now your PHP code can extract the incoming data from $_POST without having to read php://input

    <?php
  session_start();
  include('conexion.php');
  // remove line that reads php://input here.

  $nomtar=$_POST['nomtar'];
  $destar=$_POST['destar'];
  $fectar=date('Y-m-d',strtotime($_POST['fectar']));
  $usu1tar=$_SESSION['idusu'];
  $usu2tar=$_POST['usu2tar'];
// rest of code follows

That should get you going, but be aware, your code is vulnerable to SQL injection. Once you get this fixed you should refactor your code to use prepared statements.

Note: FormData can extract data directly from a form without you extracting it field by field. let formData = new FormData(document.getElementById('formId')) will do it in one operation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement