2

I want to upload a file asynchronously using jQuery - without using any PLUGIN.

JQuery is very new to me and after looking at various forums I ended up with this code :


HTML:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">


$(document).ready(function(){

    $('#myform').submit(function() {

        var fileInput = document.getElementById('file');
        var file = fileInput.files[0];
        var formData = new FormData();
        formData.append('file', file);

        $.ajax({
            type: "POST",
            url: "upload.php",
            data: formData,
            processData: false,



            contentType: 'multipart/form-data',


                beforeSend: function (x) {
                        if (x && x.overrideMimeType) {
                            x.overrideMimeType("multipart/form-data");
                        }
                },

            success:function(msg){
                    //alert( "Data Uploaded: " + msg );
                document.getElementById('display').innerHTML = msg;

                }
            });

        return false;
    });


});

</script>
</head>

<body>
<form enctype="multipart/form-data" id="myform" name="myform" method="POST">
<input name="file" type="file" id="file" name="file"/>
<input type="text" name="txtValue" value="" id="txtValue">-->
<input type="submit" value="Upload" id="button" name="button"/>

<div id="display"></div>
</form>

</body>
</html>

PHP:

<?php

$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
  $value = "success";
} 
else {
    $value = "error";
}


echo $value; 

?>

This code is not working and everytime the "display" DIV is printing "error". Please help me out.

0

4 Answers 4

1

Take a hidden div. Inside that div take a iframe and set the form's target to the iframe's id.

In jQuery. In after document ready function add a load event handler (say LEH)to the iframe. So that when the form is submitted and file is uploaded and iframe is loaded then the LEH will get called

This will act like success event.

Note: you need to make minor tweaks as for the first time when the page is loaded then also the iframe is loaded. So there will be a first time check also.

1

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).

The HTML:

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

You can do some validation if you want.

$(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
});

Now the Ajax submit with the button's click:

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

Now if you want to handle the progress.

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

SOURCE

0

You can use following plugins to upload files using ajax:

  1. jQuery Form Plugin

  2. Uploadify

The plugin in the first link provides some very useful callbacks. You can check the documentation at the given link.

0

I have user Jquery Form Plugin in my project. JQuery the raw xhr object is wrapped in jqXhr Object which doesn't have any reference to the new upload property of the xhr. Hope you can start with this below example. html:

 <input type="file" class="text-input" size="50" id="file_upload" value=""  name="file_upload"/>

var formData = new FormData($('form')[0]);
$.ajax({
url: '/files/add_file',  //server script to process data
type: 'POST',
xhr: function() {  // custom xhr
 myXhr = $.ajaxSettings.xhr();
 if(myXhr.upload){ // check if upload property exists
    //myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
dataType: 'JSON',
beforeSend: beforeSendHandler,
success: function(data) {
    if (data.error){
       showMessage(data.html, false, false);
        }
    else{
       showMessage(data.html, false, false);
setTimeout("window.location = 'path/to/after/uploading';",450)
}
},
error: function(data) {
    showMessage(data.html, false, false);
},
// Form data
data: formData,
   //Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.