0

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" }
2
  • 3
    The text input isn't inside the form. Commented Jun 13, 2022 at 22:28
  • 3
    BTW, you're never using the formData variable. You're creating a new FormData with new FormData(this) inside the click handler. Commented Jun 13, 2022 at 22:29

1 Answer 1

1

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);

      }
    });
  });
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.