Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Validate with file upload

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

like image 849
katie hudson Avatar asked Oct 05 '15 21:10

katie hudson


1 Answers

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");
    }
});
like image 179
stanley1943 Avatar answered Nov 04 '22 17:11

stanley1943