Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.

<script>
jQuery(function($){ 
    jQuery('#btn').click(function(){

        var data  = {},
            ticks = [];

        $('.ajax_elements').each(function(_, elem) {
            data[this.id] = this.value;

        });


        $.ajax({
            type  : 'POST',
            url   : 'app_process.php',
            data  : data,
            cache : false
        }).done(function(result) {
            alert(result);  
        });
    });
});
</script>
<form name="frm" enctype="multipart/form-data">
    <input type="text" name="bb"  class="ajax_elements" id="one"/>
    <input type="file" class="ajax_elements" name="passport" id="passport" />
    <input type="button" name="bttn" id="btn"  />
    </form>

here is php file code

<?php
    if($_REQUEST['passport']!=''):
        $uploaddir = 'images/';
        move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
    endif;
?>

error message

Notice: Undefined index: file in G:\xampp\htdocs\data_ajax\app_process.php on line 5

share|improve this question
    
post error.. Whatever you are getting –  Sunil Kumar Nov 20 '13 at 13:20
    
You can't upload files using AJAX, unless you either use the HTML5 file API and send the raw data or use a hidden iframe. –  Ben Fortune Nov 20 '13 at 13:21
    
yes you can. See my answer with jquery, but also possible without (see link in @vijay4vijju's answer) –  Asenar Nov 20 '13 at 13:34
    
move_uploaded_file($_FILES["passport"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport'])); may be this solve the problem –  Vipin Soni Nov 20 '13 at 13:50

2 Answers 2

My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.

This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...

<script>
$('#btn').click(function() {

    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("load", function(e){
        // stuff to do when upload is complete
    }, false);

    xhr.upload.addEventListener("progress", function(e){
        // stuff here to handle progress bars, progress percentages etc.
    }, false);

    xhr.open('POST', 'app_process.php', true);

    var formdata = new FormData();
    var file = $('#passport').get(0).files[0];

    formdata.append('passport', file);

    xhr.send(formdata);

});
</script>

And the PHP...

<?php
if (isset($_FILES['passport'])) {
    $uploaddir = 'images/';
    $upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
    exit('File not found');
}
?>

Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.

formdata.append('field', 'data');

Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.

You could also bind the upload function to the change event of the file input instead of asking for a button click...

$('#passport').change(function() { ...

Hope that helps.

share|improve this answer
    
This is the only correct/good answer in this entire thread. –  Ray Nicholus Nov 20 '13 at 15:18

There is 2 problems :

You need to add the attribute enctype="multipart/form-data" in the form tag if you want to upload files:

replace

<form name="frm">

by

<form name="frm" enctype="multipart/form-data" >

With ajax (and jquery), you cannot send file directly. But I suggest you that jquery form plugin who can help you with that

share|improve this answer
    
I would like to know why the negatives votes ^^ –  Asenar Nov 20 '13 at 13:25
    
nothing is wrong with this answer –  zzlalani Nov 20 '13 at 13:26
    
why down vote for this –  Sunil Kumar Nov 20 '13 at 13:27
    
that's the point ^^ but maybe they just read the <form> part, and not the jquery plugin suggestion, I will edit to make it more clear –  Asenar Nov 20 '13 at 13:27
    
@Asenar you pointed him at right enctype="multipart/form-data". It was missing that –  Sunil Kumar Nov 20 '13 at 13:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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