4
votes

I have been trying to get a file from ajax to php for a while without success. So I am using JQuery Validate

I have a form with several inputs (name, email etc) and one input is of type file. I perform all my validation, even on the file, and this all runs smoothly. I then come to the submitHandler function. From what I have read, there use to be issues sending files via ajax, but it is now possible. So I am trying

submitHandler: function (form) {
    var $form    = form,
        formData = new FormData(),
        params   = $form.serializeArray(),
        files    = $form.find('[name="fileOne"]')[0].files;

    $.each(files, function(i, file) {
        formData.append('uploadedFiles-' + i, file);
    });

    $.each(params, function(i, val) {
        formData.append(val.name, val.value);
    });

    $.ajax({
        type: "POST",
        url: "php/process.php",
        dataType: "json",
        data: formData
    }).done(function (response) {
        if (!response.success) {
            alert("Failed");
            console.log(response.errors);
        }
        else {
            alert("Worked");
        }
    });
    return false;
}

So I was hoping that would get my file (fileOne) and append it to my form data. However, in PHP I am simply doing this for now

try {
    if(isset($_FILES['fileOne'])){
        var_dump("IN");
    }
    else {
        var_dump("NO FILE");
    }

} catch (RuntimeException $e) {
    echo $e->getMessage();
}

Alot of times it does not even hit this PHP, because the form submits with the url getting all the data (this usually happens when the JQuery has an error). When I do get it working, I get the output No File.

So how can I send my uploaded file with the rest of my form data, so I can process it in PHP?

Thanks

1
You are not doing anything with your formData. And using try/catch here does make absolutely no sense – you have nothing there that would throw any exception.CBroe
My mistake, showed an old version of data. Have updated it to show that I am passing formDatakatie hudson
If you want to send all your form fields, then all you have to do is pass your form element to FormData.CBroe

1 Answers

5
votes

You did not set contentType: false, processData: false

 $.ajax({
    type: "POST",
    url: "php/process.php",
    dataType: "json",
    data: formData,
    mimeType: "multipart/form-data",
    contentType: false,
    processData: false
}).done(function (response) {
    if (!response.success) {
        alert("Failed");
        console.log(response.errors);
    }
    else {
        alert("Worked");
    }
});