1

I was trying to upload file on server using php with jQuery's ajax() function. Below is the code which I was trying. Things worked fine when I wrote PHP code on same page without jQuery, so there is no doubt that file upload is working.

HTML


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(function() {
        $("form").submit(function(e){
            e.preventDefault();

            var fd = new FormData();    
            fd.append("files", $("#fileinput").prop("files"));
            $.ajax({
                url: "imgupload_.php", 
                type:"POST",
                processData: false,
                contentType: false,
                data: fd,
                success: function(result){
                    alert(result);
                }
            });
        });
    });
</script>
<form method="POST" action="#" enctype="multipart/form-data">
    <input type='file' name='files' id="fileinput"/>
    <input type='submit' value='Submit' name='submit'/>
</form>

imgupload_.php

if(isset($_POST["submit"])) {
    $target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["files"]["name"]);

    if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

If you want any other info please comment below.

1 Answer 1

2

You're checking if(isset($_POST["submit"])) but this is not set.

Instead of just this:

var fd = new FormData();

Use this to pull in any non-file input values (such as your submit button.)

var fd = new FormData(this);
Sign up to request clarification or add additional context in comments.

1 Comment

Yupp. If I replace if(isset($_POST["submit"])) with if($_SERVER["REQUEST_METHOD"] == "POST") and add this in FormData, it works. Thank you sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.