I have a html form to upload a file (I use php to do the upload). I want to show the result from the upload using ajax (I'm new to it, so I may miss something really simple), however, my code currently does not do that. I read a lot and tried many things, but in vain, so finally I decided to ask for help.
HTML & AJAX
<script type="text/javascript">
( function( $ ) {
$('form').ajaxForm({
type: "POST",
url: "Upload.php",
data: $('#upload').serialize(),
dataType: "html",
timeout: 15000,
success: function( data ) {
alert( data );
}
});
})( jQuery );
</script>
<form enctype="multipart/form-data" method="post" id="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<h2>File to upload</h2>
<input name="userfile" type="file" class='file'/>
<input type="submit" name="send" value="Upload File" />
</form>
PHP
try
{
if ( $_POST["send"] )
{
if ( isset( $_FILES['userfile'] ) )
{
require_once "FileUploader.php";
$fileUploader = new FileUploader();
if ( $fileUploader->moveFile() )
{
echo "Success";
}
echo "Error";
}
}
}
catch( \Exception $e )
{
echo "
" . $e->getMessage();
exit();
}
Currently, alert( data ); results in the message NULL. There are no errors in the console.
You forgot to set the Path where you post your File!
AS I mentioned in comment, serialize() can not pass FILE, and you could check this with a simple var_dump($_POST);
in your upload.php. you can pass your file in an instance of FormData() like below code
another problem is in your upload.php that uses FileUploader.php and I don't know what kind of code it has, but I try to fix your JQuery AJAX code with a sample of upload.php for you
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$( function() {
$('form').submit(function(){
var form_data = new FormData(this);
$.ajax({
type: "POST",
url: "upload.php",
data: {userfile:JSON.stringify(form_data)},
dataType: "json",
timeout: 15000,
success: function( data ) {
console.log( data );
}
});
return false;
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post" id="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<h2>File to upload</h2>
<input name="userfile" type="file" class='file'/>
<input type="submit" name="send" value="Upload File" />
</form>
</body>
</html>
your upload.php with some optimizations
try
{
if ( isset( $_FILES['userfile'] ) && $_POST["userfile"] )
{
require_once "FileUploader.php";
$fileUploader = new FileUploader();
if ( $fileUploader->moveFile() )
{
echo "Success";
}
echo "Error";
}
}
catch( \Exception $e )
{
echo "
" . $e->getMessage();
exit();
}