0

I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows: My HTML:

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

Pretty straight forward.

My PHP storeSales.php

    if ($_FILES["file"]["name"] != NULL) { 
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');

and my .js:

    $(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here"); 
}

$.ajax({
    url: 'storeSales.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

    success: function(result)
{
    console.log($.ajaxSettings.xhr().upload);
    alert(result);
},

    // Form data
    data: formData,
    //Options to tell jQuery not to process data or worry about content-type.
    cache: false,
    contentType: false,
    processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
    $('progress').attr({value:e.loaded,max:e.total});
}
}

When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?

1
  • You figure anything out? Was my answer helpful? Commented Dec 9, 2013 at 22:15

1 Answer 1

2

You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.

Try Uploadify: http://www.uploadify.com/

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

Comments

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.