1

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

4
  • post error.. Whatever you are getting Commented Nov 20, 2013 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. Commented Nov 20, 2013 at 13:21
  • yes you can. See my answer with jquery, but also possible without (see link in @vijay4vijju's answer) Commented Nov 20, 2013 at 13:34
  • move_uploaded_file($_FILES["passport"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport'])); may be this solve the problem Commented Nov 20, 2013 at 13:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

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 you pointed him at right enctype="multipart/form-data". It was missing that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.