Hey I am trying to submit a form to mysql db. The form is inside a modal though. The data is then sent to an ajax handler via ajax and a php function is ran. Everytime the word 'file' is written in the handler, i get an error. Here is my form, ajax and handler.
Form input:
<div class="form-group">
<label>Image</label>
<input type="file" class="addInput" name="image" id="newImage" placeholder="">
</div>
Javascript/Ajax
var name = $('#newName').val();
var description = $('#newDescription').val();
var notes = $('#newNotes').val();
var status = ($('#newStatus').is(":checked") ? 'active' : '');
var slug = $('#newSlug').val();
var start_date = $('#newStartDate').val();
var end_date = $('#newEndDate').val();
var image = $('#newImage').val();
let data = {
action: 'NewEventExhibition',
name: name,
description: description,
notes: notes,
status: status,
slug: slug,
start_date: start_date,
end_date: end_date,
image: image,
event_code: '<?=$code?>'
};
console.log(data);
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: data,
success: function(response) {
console.log(response);
},
fail: function(response) {
console.log(response);
}
})
Handler
$added = $image = $filename = $imagefile = $imagefilesuccess1 = $imagefilewarning1 = NULL;
if(!empty($_POST['image'])){
$filename=($_SERVER['DOCUMENT_ROOT']."/assets/images/" . $_FILES["file"]["name"]);
$imagefile=($_FILES["file"]["name"]);
$path="/assets/images/".$imagefile."";
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "PNG");
$tmp = explode(".", $imagefile);
$extension = end($tmp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/JPG")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 7000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0){
$imagefilewarning1 = "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else {
$imagefilesuccess1 = "an image file was uploaded: <strong>" . $_FILES["file"]["name"] . "</strong>";
if (file_exists("uploads/" . $_FILES["file"]["name"])){
$imagefilewarning2 = $_FILES["file"]["name"] . " already exists. ";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
$imagefilesuccess4 = " and is stored in: <strong>" . $path . "</strong>";
}
}
}
else {
$imagefilewarning3 = "no image file was uploaded";
}
$image = ($imagefile == '') ? $_POST['file'] : $imagefile;
}
I included just the image code in the ajax handler. The $image
variable at the bottom is the one i use to upload.