Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading an image without form submitting

Tags:

jquery

php

<input type='file' name='inputfile' id='inputfile'>

I'm trying to upload an image without a form submitting - just after input file is changed:

$('#inputfile').change(function(){
    $.ajax({
        url: "pro-img-disk.php",
        type: "POST",
        data:  new FormData('#inpufile'),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            console.log(data);
        }
    });
});

PHP

$src = $_FILES['inputfile']['tmp_name'];
$targ = "../images/".$_FILES['inputfile']['name'];
move_uploaded_file($src, $targ);

Error:
Undefined index: inputfile...

Any help?

like image 488
qadenza Avatar asked Dec 06 '22 14:12

qadenza


2 Answers

See to the following changes:

<input type='file' name='inputfile' id='inputfile'>

Here's how you should have sent the ajax request:

$(document).ready(function() {
    $('#inputfile').change(function(){
        var file_data = $('#inputfile').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        $.ajax({
            url: "pro-img-disk.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});

And lastly, here's how you should have processed the form data:

$src = $_FILES['file']['tmp_name'];
$targ = "../images/".$_FILES['file']['name'];
move_uploaded_file($src, $targ);
like image 143
SpaceBaar Avatar answered Jan 29 '23 03:01

SpaceBaar


Try this:

var file_data = $('#inputfile').prop('files')[0];
var form_data = new FormData();                     // Create a form
form_data.append('inputfile', file_data);           // append file to form

$.ajax({
        url: "pro-img-disk.php",
        type        : 'post',
        cache       : false,
        contentType : false,
        processData : false,
        data        : form_data,                         
        success     : function(response){
            alert(response);
        }
 });

in php you can get the file data like:

$_FILES['inputfile']
like image 20
Mayank Pandeyz Avatar answered Jan 29 '23 02:01

Mayank Pandeyz