简体   繁体   中英

ajax jquery file upload not working

I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined . I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working .The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.

My code is below:

$(document).ready(function()
{ 
    //for checking whether the file queue contain files or not
    var files;
    // Add events
    $('input[type=file]').on('change', prepareUpload);

    // Grab the files 
    function prepareUpload(event)
    {
        files = event.target.files;
        alert(files);
    }
    $("#file-form").on('submit',uploadFiles);
    function uploadFiles(event)
    {
        event.stopPropagation();  
        event.preventDefault(); 

        // Create a formdata object and add the files
        var data = new FormData();
        $.each(files, function(key, value)
        {
            data.append(key, value);
            //alert(key+' '+ value);
        });
        $.ajax({
            url: 'module/portal/filesharing/upload.php?files',
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, 
            contentType: false, 
            success: function(data, textStatus, jqXHR)
            {
                if(typeof data.error === 'undefined')
                {
                    // Success so call function to process the form
                    submitForm(event, data);
                }
                else
                {
                    console.log('ERRORS: ' + data.error);
                }
            }
        });
        function submitForm(event, data)
        {
            // Create a jQuery object 
            $form = $(event.target);

            // Serialize the form data
            var formData = $form.serialize();//controller stops here

            // sterilise the file names
            $.each(data.files, function(key, value)
            {
                formData = formData + '&filenames[]=' + value;
            });

            $.ajax({
                url: 'update.php',
                type: 'POST',
                data: formData,
                cache: false,
                dataType: 'json',
                success: function(data, textStatus, jqXHR)
                {
                    if(typeof data.error === 'undefined')
                    {
                        // Success so call function to process the form
                        console.log('SUCCESS: ' + data.success);
                    }
                    else
                    {
                        // Handle errors here
                        console.log('ERRORS: ' + data.error);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    // Handle errors here
                    console.log('ERRORS: ' + textStatus);
                },
                complete: function()
                {
                    // STOP LOADING SPINNER
                }
            });
        }
    }  
});    
</script>

Html:

<form id='file-form' action="" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file" id="filename" ><br>
    <input type="submit"  id='upload' value="Upload file">
</form>

My update.php:

$data = array();
if(isset($_GET['files']))
{    
    $error = false;
    $files = array();
    $uploaddir = 'module/portal/filesharing/upload/';
    foreach($_FILES as $file)
    {
        if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
        {
            $files[] = $uploaddir .$file['name'];
        }
        else
        {
            $error = true;
        }
    }
    $data = ($error) ? array('error' => 'There was an error uploading your files') :     array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer

Maybe your problem is this one, please check this out how to get the uploaded image path in php and ajax?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM