I am trying to upload a file to a folder using jQuery Ajax and PHP.
This is the form I use to upload a file.
<form id="data" method="post" enctype="multipart/form-data">
<textarea name="txtmessage" placeholder="Write your post here"></textarea>
</br>
<label>Subject:</label>
<input type="text" id="subcode" name="subcode" placeholder="Enter Subject Code e.g.: BIT304">
<br/>
<input name="img" type="file" /><br/>
<button type="submit" class="btn btn-default" id="btnAddAction" name="submit" value="Submit">Share</button>
</form>
<script>
$("form#data").submit(function(event){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#comment-list-box").append(returndata);
$("form#data")[0].reset();
$("#loaderIcon").hide();
},
error:function (){}
});
});
</script>
and this is formprocessing.php to process the form.
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_SESSION['id'];
$subcode = $_POST['subcode'];
$txtmessage = $_POST['txtmessage'];
$file = $_FILES['img']['name'];
if($file != "") {
$subcode = "General";
$target = "uploads/";
$fileTarget = $target.$file;
$tempFileName = $FILES["img"]["tmp_name"];
$infile = move_uploaded_file($tempFileName,$fileTarget);
if($infile){
$result= mysql_query("INSERT INTO fyp_comment(message, subject, userid, timeDate, image) VALUES('$txtmessage', '$subcode', '$id', now(), '$fileTarget')");
if($result){
$insert_id = mysql_insert_id();
}
}
}
else{
$result = mysql_query("INSERT INTO fyp_comment(message, subject, userid, timeDate) VALUES('$txtmessage', '$subcode', '$id', now())");
if($result){
$insert_id = mysql_insert_id();
}
}
?>
However, I could not upload the files to the directory after i submit the form and the other part are not stored in the database. On the other hand, if i submit the form without a file the text are all stored into the database. What did I do wrong in this case? been thinking about this for an hour now . Thanks