Home > front end >  Why is my fetch function sending empty strings?
Why is my fetch function sending empty strings?

Time:09-23

form.addEventListener('submit', (e) => {
    e.preventDefault();
    var name = nameInput.value;
    var email = emailInput.value;
    var amount = amountInput.value;
    console.log(name);
    let data = {
        name : name,
        email : email,
        amount : amount,
    }
    fetch('validator.php', {
        method : 'POST',
        body : JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json'
        }
    }).then(function(response) {
        return response.text();
    }).then(function(text) {
        console.log(text);
    }).catch(function(error){
        console.error(error);
    })
});

Manually inputting a name in the PHP file makes it work, so the problem is clearly how the information is being sent. It's not in the HTML because of the console.log, so any ideas?

<?php
    // User data to be displayed later
    $name = $_POST["name"];
    $email = $_POST["email"];
    $amount = $_POST["amount"];
    // Check for email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Please enter a valid email";
    }
    // JSON array
    $info = array($name,$email,$amount);
    json_encode($info);
?>

Up until the console.log, the information is correct, and it prints correctly. However, I'm getting this error on my browser:

Notice: Undefined index: name in C:\laragon\www\validator.php on line 4 Notice: Undefined index: email in C:\laragon\www\validator.php on line 5

Notice: Undefined index: amount in C:\laragon\www\validator.php on line 6 Please enter a valid email

Here's the html of the form I am using:

<form action="validation.php" method="POST"  id="form">
    <label for="name"  style="color: #1D1C52; font-weight: bold;">Name</label>
    <div >
        <input
          type="name"
          id="name"
          name="name"
          
          required
        />
 
      </div>
      <label for="email"  style="color: #1D1C52; font-weight: bold;">Email</label>
      <div >
        <input
          type="email"
          id="email"
          name="email"
          
          required
        />

      </div>
      <label for="amount"  style="color: #1D1C52; font-weight: bold;">Amount</label>
      <div >
        <input
          type="number"
          id="amount"
          name="amount"
          
          required
        />
      </div>

    <div >
    <div >
    <div >
        <div  id="clearButton">Clear fields</div>
    </div>
    <div >
        <button type="submit"  style="color: white; background-color: #1D1C52;" id="submitButton">Submit</button>
    </div>

    </div>                  
  </form>

CodePudding user response:

typically instead of sending json to PHP, you'll want to make a form object.

const formData = new FormData();
const nameField = document.querySelector('input[name="name"]');
formData.append('name', nameField.value);

then use formData as your body, and don't set the fetch's content type at all.

but, since you are literally sending a form, there is an even easier way. you can make a formData from a form element.

const formData = new FormData(formElement);

then just use that as your body.

alternately if you must send your data as JSON, rather than a normal request, you will need to parse the request directly, rather than using $_POST variables in PHP.

$data = json_decode(file_get_contents('php://input'), true);
  • Related