Good Morning,
I searched all over with no luck for the answer to my problem. I would like to use jquery, but have tried with 'regular' Javascript with little success.
Goal
I would like to upload a file (just one) via ajax (asynchronous) to a php server which will consume the file (txt).
Problem
The script will not call the php script, nor will the file upload. There are no javascript errors and it seams that the script runs through just fine. In chrome, process.php does not show up in the network section, so I am not sure if it is from the script or an error within my php.
General Information
Browser: Chrome Version 26.0.1410.64 m
wamp server (php, mysql)
Bootstrap for layout
Code
index:
<div class="span12" id="upload_form_div" style="display: block;">
<form id="upload_form" enctype="multipart/form-data" class="upload_form">
<fieldset>
<legend>
Please select a file to parse and merge with the database.
</legend>
<p>
<label for="files">File:</label>
<input type="file" class="text" id="files" name="file">
</p>
<p>
<input type="button" value="Start Parse">
</p>
</fieldset>
</form>
</div>
I am including the jquery.js, app.js (script file for upload), and bootstrap.min.js. Just thought it wasn't necessary to show the full html markup.
Script File:
$(function(){
$("#progressbar").hide();
});
function showProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#progressbar').progressbar("option", "value", percentComplete );
}
}
$(':button').click(function(){
var fileIn = $("#files")[0];
//Has any file been selected yet?
if (fileIn.files === undefined || fileIn.files.length == 0) {
alert("Please select a file");
return;
}
//We will upload only one file
var file = fileIn.files[0];
console.log(file);
//Show the progress bar
$("#progressbar").show();
$.ajax({
url: 'process.php', //server script to process data
type: 'POST',
data: file,
contentType: file.type,
processData: false,
success: function(){
$("#progressbar").hide();
},
error: function(){
$("#progressbar").hide();
alert("Failed");
//alert(xhr.responseText);
},
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
//myXhr.upload.addEventListener('progress',showProgress, false); // for handling the progress of the upload
//console.log($.ajaxSettings.xhr().upload);
console.log(myXhr.responseText);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
}
});
});
This is straight copy paste so I commented out some of the trouble shooting lines.
PHP
<?php
set_error_handler("E_ALL");
$upload_directory = "files/";
move_uploaded_file($_FILES['file']['tmp_name'], $upload_directory . $_FILES['file']['name']);
?>
The php file will do more, but I am just trying to get the file to upload at this point.
If anyone needs more information just let me know and I will do my best to supply the information.