-1

I have the following code for an HTML form:

<form id="idForm" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

and the following Javascript code on the same page where the form is located. Also, this code is written below the form code:

$("#idForm").submit(function() {
    alert("hi");
    var url = "submit.php"; 

    $.ajax({
        type: "POST",
        url: url,
        data: $("#idForm").serialize(),
        success: function(data) {
            alert(data);
        }
    });

    return false;
});

And here is the PHP code that I'm using to see if the form data is being posted:

if (isset($_FILES['image'])) {
    $image = $_FILES['image'];
    echo $image;
}

if (isset($_POST['first'])) {
    $name = $_POST['first'];
    echo $name;
}

With the above code, it seems as though the attached file is not being sent to the PHP file. Only the values are being sent, since they are echoed when I inspected the element using Google Chrome dev tool.

I want to be able to post both text value and files to the PHP file for processing.

Why am I getting this problem? How do I fix this?

Also, as part of the solution, I want to prevent the page from being refreshed when the submit button is clicked.

Thanks much!

ITWitch
  • 1,729
  • 5
  • 20
  • 38
maraj
  • 51
  • 1
  • 1
  • 9
  • Data from file select elements is not serialized.http://api.jquery.com/serialize/ – CoderLim Mar 31 '17 at 01:51
  • 1
    Possible duplicate of [Uploading both data and files in one form using Ajax?](http://stackoverflow.com/q/10899384/1255289) – miken32 Mar 31 '17 at 02:01
  • "i want that the submit button, when clicked, that the page does not refresh" pass the event to your handler and then `e.preventDefault()` instead of `return false` – miken32 Mar 31 '17 at 02:02
  • add this to your ajax `processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType` – guradio Mar 31 '17 at 02:04
  • currently, the page does not load... i added both processData: false, and contentType: false, but now after doing that, nothing is being posted...not even the text values... – maraj Mar 31 '17 at 02:20

1 Answers1

1

Unfortunately input[type='file'] cannot be submitted by .serialize(), you have to manipulate by formData. You will find a very good formData example in here

Community
  • 1
  • 1