I have a form that has a multiple input data and 4 input image,how do i post them using Ajax ? here is my set of code i have tried...
HTML
<form action="<?php echo base_url('link')?>/to/controller" method="POST" id="frm-update" enctype="multipart/form-data">
<!-- Normal Post -->
<input type="text" name="input1" id="input1" class="form-control">Normal Input1
<input type="text" name="input2" id="input2" class="form-control">Normal Input2
<input type="text" name="input3" id="input3" class="form-control">Normal Input3
<input type="text" name="input4" id="input4" class="form-control">Normal Input4
<!-- Image Post -->
<input type="file" name="image1" id="image1" class="form-control">Image 1
<input type="file" name="image2" id="image2" class="form-control">Image 2
<input type="file" name="image3" id="image3" class="form-control">Image 3
<input type="file" name="image4" id="image4" class="form-control">Image 4
<button type="submit" class="btn btn-success">Save
Jquery
<script>
$("#frm-update").validate({
ignore: ':hidden:not(.chzn)',
errorPlacement: function (error, element) {
if (element.is(":hidden")) {
element.next().parent().append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: $("#frm-update").attr('action'),
data: $("#frm-update").serialize(),
</script>
what i've been thinking is,what if i used new FormData(this),do all input on my form is saved ? or is it just the image ?
Use FormData
instead of serialize()
$("#frm-update").validate({
ignore: ':hidden:not(.chzn)',
errorPlacement: function (error, element) {
if (element.is(":hidden")) {
element.next().parent().append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
var data = new FormData(form);
$.ajax({
url: $(form).attr('action'),
data: data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
// data passed from php
console.log(data);
}
});
}
});
Then in your PHP
you can do something like the following
<?php
// get values of input through $_POST
// move uploaded files to a directory with move_uploaded_file() function
// get inputs using $_POST
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$input3 = $_POST['input3'];
$input4 = $_POST['input4'];
// get files using $_FILES
$image1 = $_FILES['image1']['name'];
$image2 = $_FILES['image2']['name'];
$image3 = $_FILES['image3']['name'];
$image4 = $_FILES['image4']['name'];
// save values to the database
?>