I am working on a form which need to insert some data with an image without reloading the page. In my side everything is working fine when there is no image filed in the form, but if there is an <input type="file">
in my form, then my code is not passing the file/image information. Can you guys please teach me what to add in my code to upload or pass image please?
My Code HTML Form
<form action="action.php" method="POST" enctype="multipart/form-data" id="myform">
<input type="hidden" value="access" name="label">
<input type="text" name="one">
<input type="text" name="two">
<input type="file" name="image">
<button type="submit" id="mybtn">Add Data</button>
</form>
<div id="myresult"></div>
My JavaScript
$('#mybtn').click( function(){
$.post(
$('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(result) {
// Some Stuff...
}
);
});
My PHP
include 'database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$label = ["access"];
if (in_array($_POST['label'], $label)) {
switch ($_POST['label']) {
case 'access':
$one = $_POST['one'];
$two = $_POST['two'];
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_temp = $_FILES['image']['tmp_name'];
$error = [];
$valid = [];
$flag1 = $flag2 = $flag3 = false;
if (!empty($one)) {
// Some validation
$flag1 = true;
} else {
$flag1 = false;
}
if (!empty($two)) {
// Some validation
$flag2 = true;
} else {
$flag2 = false;
}
if (!empty($file_name)) {
// Some validation
$flag3 = true;
} else {
$flag3 = false;
}
if ($flag1 && $flag2 && $flag3) {
// move_uploaded_file() + Insert All data
if ($result) {
$valid[] = "Data added successfully!";
} else {
$error[] = "Please try again later!";
}
} else {
$error[] = "Something went wrong!";
}
// ALERT MESSAGE [error] and [valid]
if (!empty($error)) {
foreach ($error as $value) {
echo json_encode($value);
}
}
if (!empty($valid)) {
foreach ($valid as $value) {
echo json_encode($value);
}
}
break;
default:
# code...
break;
}
}
}
This code works perfectly without reloading page while there are no input type file. I want to know what code I have to add in my JavaScript section to execute the code successfully with an input type file.
$('#dataBtnIMG').click( function(){
var form = $('#dataFormIMG');
var formData = new FormData($('#dataFormIMG')[0]);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: formData,
cache: false,
contentType: false,
processData: false,
success:function(result) {
// Some Stuff
}
});
});