I am trying to submit the form using ajax but it gives always error and data is not submitting into the database.
Please have a look at my code. I have searched about that but didn’t get any solution actually I am new in Codeigniter didn’t have much knowledge about that. I very thankful is someone helps me to solve this error thanks.
jQuery / AJAX Code:
<script>
$(document).ready(function(){
$("#personal-info").submit(function(e){
e.preventDefault();
var fname = $("#fname").val();;
var email_address= $("#email_address").val();
var comment= $("#comment").val();
$.ajax({
type: "POST",
url: '<?= site_url('Book/contact')?>',
data: {fname:fname,email_address:email_address,comment:comment},
success:function(data)
{
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Message send successfuly',
showConfirmButton: false,
timer: 1500
});
},
error:function()
{
Swal.fire({
position: 'top-end',
icon: 'error',
title: 'Message Sending Fale Please try again',
showConfirmButton: false,
timer: 1500
});
}
});
});
});
</script>
VIEW :
<div class="row">
<div class="col-lg-5 offset-lg-6 col-md-12">
<div class="section-title v2">
<h2>Write to us</h2>
</div>
<form id="personal-info" action="" method="post">
<div class="form-control-wrap">
<div id="message" class="alert alert-danger alert-dismissible fade"></div>
<div class="form-group">
<input type="text" class="form-control" id="fname" placeholder="Name*" name="fname" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_address" placeholder="email*" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" rows="8" name="comment" id="comment" placeholder="Your Message" required></textarea>
</div>
<div class="form-group">
<button type="submit" id="send_form" class="btn v7">Send Message</button>
</div>
</div>
</form>
</div>
</div>
Controller :
public function contact()
{
$data = array(
'name' => $this->input->post('fname'),
'emall' => $this->input->post('email'),
'message' => $this->input->post('message'),
);
$this->db->insert('contact',$data);
echo json_encode($data);
}
3
Answers
jQuery / AJAX Code:
Controller :
Your ajax call’s data
email_address
is not matching php’s$this->input->post('email')
.Your url query is getting builded up like
...&email_address=USER_INPUT
which is not matching at the recieving end ie:...->post('email')
it should be..->post('email_address')
and thecomment
field is sent ascomment
but recieved as..->post('message')
which is also incorrect.This should work