0

file upload works with ajax and php, but does not return responses! in the upload.php page is displayed:

uploaded succesfully!

html:

<form action="upload.php" method="post" enctype="multipart/form-data" id="form">
        <div style="padding: 15px;">
            <input type="file" name="file" id="file">
        </div>
        <div style="padding: 15px">
            <input type="submit" value="Upload" id="upload">
        </div>
</form>

ajax:

$(document).ready(function () {
        $('#form').on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,

                success: function (response) {
                    alert(response);
                }
            })
        })
})

php:

if (isset($_FILES['file'])) {    
    $file_destination = "uploads/IMG-" . date("Y-m-d") . time() . ".jpg";

    if (move_uploaded_file($_FILES['file']['tmp_name'], $file_destination)) {
        echo "uploaded succesfully!";
    }
}
hf_vrp
  • 3
  • 2

1 Answers1

0

issue exist on client side use this html and java script code hope your issue will be resolved

<form action="#" enctype="multipart/form-data" id="form">
<div style="padding: 15px;">
    <input type="file" name="file" id="file">
</div>
<div style="padding: 15px">
    <button value="Upload" id="upload">Submit</button>
</div>
</form>

js part

$(document).ready(function () {
$('#upload').on('click', function (e) {
    e.preventDefault();
    var formData = new FormData();
    formData.append('file', $('#file')[0].files[0]);
    $.ajax({
        url: "upload.php",
        type: "POST",
        data: formData,
        contentType: false,
        // cache: false,
        processData: false,

        success: function (response) {
            alert(response);
        }
    });
}); });
Leenard
  • 63
  • 1
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 20 '22 at 12:08
  • it works! thank you engineer – hf_vrp Jan 20 '22 at 15:36