I'm implementing an ajax contact form in Codeigniter. Can't seem to figure out what my issue is. When running the script through Firebug, there is a POST error in jquery.min.js which doesn't seem to make much sense. Maybe there's a syntax error I'm missing?
Here is my ajax JS:
$(document).ready(function() {
//Ajax contact form
$('#submit').click(function() {
var form_data = {
first_name : $('.first_name').val(),
last_name : $('.last_name').val(),
email : $('.email').val(),
message : $('.message').val(),
ajax : '1'
};
$.ajax({
type : 'POST',
url : "http://localhost/web/hfs/home/contact",
async : false,
data : form_data,
success : function(msg) {
$('#left-container.thankyou').html(msg);
}
});
// end ajax
return false;
});
});
And here is my controller function:
public function contact() {
if ($this -> input -> post('ajax') == '1') {
$this -> form_validation -> set_rules('first_name', 'First Name', 'required|min_length[1]');
$this -> form_validation -> set_rules('last_name', 'Last Name', 'required|min_length[1]');
$this -> form_validation -> set_rules('email', 'Email', 'required|valid_email');
$this -> form_validation -> set_rules('message', 'Message', 'required|min_length[5]');
$this->form_validation->set_message('required', 'Please fill in the fields');
if ($this -> form_validation -> run() == FALSE) {
echo validation_errors();
} else {
echo "Thanks for contacting!";
}
}
}
This works. Listen for the submit event on the form and use data : $(this).serialize()
.
<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<form id="myform">
<input type="text" name="a" value="Some value in A" id="a" />
<input type="text" name="b" value="Some value in B" id="b" /></div>
<input type="submit" value="Submit" />
</form>
<p id="thankyou"></p>
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function() {
$.ajax({
type : 'POST',
url : "http://localhost/web/hfs/home/contact",
async : false,
data : $(this).serialize(),
success : function(msg) {
$('#thankyou').html(msg);
}
});
return false;
});
});
</script>
</body>
</html>