javascript – how did i can send form data with $.post()?-ThrowExceptions

Exception or error:

I can send form_data for uploaded file with $.ajax. but when I used (input: file) how did I can send form data that be an image file that chose with input to PHP with $.post()?

<input type="file" id="img" name="img" accept="image/jpg,image/jpeg" style="display: none">
How to solve:

You’ll need to make the method of form POST and enctype="multipart/form-data"

<form method="POST" action="URL" enctype="multipart/form-data">
<input type="file" id="img" name="img" accept="image/jpg,image/jpeg" style="display: none">
</form>

Then You can get the uploaded image as $_FILES where your form is posting.

###

<input type="file" id="img" name="img" accept="image/jpg,image/jpeg">

You’ll need to get the file by onchange event of input

$(document).ready(function() {
    $('#img').change(function(){
        var file_data = $('#img').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        $.ajax({
            url: "fileUpload.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *