I am trying to post a file that I upload through ajax. My file uploading and validation works without javascript when the simple post is used. But when javascript is turned on and the form has to be submitted through ajax, it doesn't work. I believe it is a problem with the way I am handling the file upload through ajax but I can't figure out what the problem is.
JQuery (ajax here):
var first_name = $('#first-name').val();
var last_name = $('#last-name').val();
var school = $('#school-register').val();
var formData = new FormData('#transcript');
var url="post.php";
$.ajax({
type: 'POST',
url: url,
data: {first_name: first_name,last_name: last_name,school:school,file:formData}
})
.done(function(response_data)
{
alert(response_data);
});
return false;
HTML Form:
<form id="animate1" enctype="multipart/form-data" method="post" action="post.php">
<input id="first-name" name="first_name" type="text" value="" placeholder="First Name" maxlength="100">
<input id="last-name" name="last_name" type="text" value="" placeholder="Last Name" maxlength="100">
<input id="school-register" name="school" type="text" value="" placeholder="High School" maxlength="100">
<label for="transcript">Transcript</label><input type="file" id="transcript" name="file">
PHP:
if ((isset($_POST['first_name'])) && (strlen(trim($_POST['first_name'])) > 0))
{
$first_name = stripslashes(strip_tags($_POST['first_name']));
}
else
{
$msg = "Student's first name required!";
$_SESSION['msg'] = $msg;
$url = "noJS.php";
header("Location: $url");
exit;
}
Similarly for the last name and school name.
PHP for the file:
if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fInfo,$_FILES['file']['tmp_name']);
$attach = false;
switch($mime)
{
case 'application/pdf':
$attach = true;
break;
default:
$msg = "Wrong file format of transcript (please upload a PDF file)!";
$_SESSION['msg'] = $msg;
$url = "noJS.php";
header("Location: $url");
exit;
}
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
}