S S S S -4 years ago 59
jQuery Question

image upload jquery without form

I have a html like this.

<div id="cb">
<img src="datat:image/jpeg;base64/9ikdsaasdflaljkf" class ="0">

I am trying to upload the file on button click without form submit. I am following a tutorial which says

var file = $("#cb")[0].files[0];

But this line I am not getting any value. Can anybody help me.

Answer Source

Try this:

    $('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
         $('#pic').val('');                     /* Clear the file container */

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>


    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
            echo "File Uploaded Successfully";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download