Home > Net >  Data not sending to php JS/FormData/AJAX using PHP
Data not sending to php JS/FormData/AJAX using PHP

Time:06-19

I am trying to send a file to my DB together with text using this:


let formData = new FormData($('#image_form')[0]);
formData.append("message", $('#messageInput').val());

        $(document).ready(function() {
            $('#image_form').submit(function(e) {
                e.preventDefault();  
               $.ajax({  
                    url: "https://example.com/test.php",  
                    type: "POST",  
                    data: new FormData(this),  
                    contentType: false,  
                    processData:false,  
                    success: function(status) {
                        $('#result').append(status);
                        
                    }
                });
            });
        });

That's the DOM

<form id="image_form" enctype="multipart/form-data">
        <input type="file" name="files[]" id="files[]" multiple >
        <input type="submit" name="submit" is="submit" id="submit"/>
    </form>

<input type="text" name="message" id="messageInput">

PHP:

<?php 

$file = $_FILES['files'];
$message = $_POST['message'];

var_dump($_POST);

?>

The Image is received by php and can be display. But the Text is not.

Besides the Image, the php script outputs:

array(1) { ["submit"]=> string(6) "Submit" }

CodePudding user response:

You need to assign formData inside the submit handler, so it gets the values after the user has submitted the form.

$(document).ready(function() {
  $('#image_form').submit(function(e) {
    e.preventDefault();
    let formData = new FormData($('#image_form')[0]);
    formData.append("message", $('#messageInput').val());

    $.ajax({
      url: "https://example.com/test.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      success: function(status) {
        $('#result').append(status);

      }
    });
  });
});

  • Related