javascriptphpajax

undefined index when using ajax to upload file


Here is my html:

<form id="uploadimage" name="form" action="" enctype="multipart/form-data">
    <input type="file" name="files" id="file"  />
    <input type="submit" value="Upload">
</form>

Here is my JavaScript code:

$(document).ready(function (e) {
    $("#uploadimage").submit(function(e) {
        e.preventDefault();
        $("#message").empty();
        $('#loading').show();
        $.ajax({
            url: "ajax_php_file.php", // Url to which the request is send
            type: "POST",             // Type of request to be send, called as method
            data:new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function(data)   // A function to be called if request succeeds
            {
                $('#loading').hide();
                $("#message").html(data);
            }
        });
    });
});

I am trying to upload file using ajax. The JavaScript is sending the data to the PHP file correctly but the PHP code shows error undefined index files. So, can you tell me what I am doing wrong?

Here is PHP file code:

<?php

               $filetype=$_FILES["files"]["type"];


?>

    

Solution

  • I was getting same error - uncaught typeerror: cannot read property 'files' of undefined with jquery mobile jquery.mobile-1.4.5.js and jquery.mobile-1.4.5.js for ajay file upload.

    As a documentation of jquery mobile ajax file uploading not supported but it working with jquery library 2.1.1

    Please replace jquery.mobile-1.4.5.js to https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js

    Thanks