I'm trying to use ajax within my contact form in a codeigniter app. I have it to where the ajax call is made, but no post data is being sent to the server. I can't figure out why. Please help.
I do have some returns in there, but they do nothing. Also, $this->input->post('name') is null.
Form view
<?php
echo form_open('welcome/submit_contact');
echo form_error('name');
echo form_label('Name', 'name'"');
echo form_input('name', set_value('name'), 'id="name);
echo form_error('email');
echo form_label('Email', 'email');
echo form_input('email', set_value('email'), 'id="email"');
echo form_error('phone');
echo form_label('Phone', 'phone');
echo form_input('phone', set_value('phone'), 'id="phone"');
#echo '<h5>Do not start with "1" and no dashes.</h5>';
echo form_error('message');
echo form_label('Message', 'message');
echo form_textarea('message', set_value('message'), 'id="message"');
$submitData = array(
'name' => 'submit',
'value' => 'Submit',
'id' => 'button'
);
echo form_submit($submitData);
echo form_close();
?>
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
success: function(msg) {
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
alert(msg);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Controller function
function submit_contact()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 class="bad">', '</h4>');
$name = $this->input->post('name');
echo "name = ".$name;
$this->form_validation->set_rules('name', 'Name', 'trim|required|alpha_dash|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('phone', 'Phone' , 'trim|integer|exact_length[10]|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|max_length[1000]|xss_clean');
// there are validation errors
if($this->form_validation->run() == FALSE)
{
return "error";
}
else // there are no validation errors
{
/*************************
need to actually send the email
*************************/
return null;
}
}
EDIT: I've updated the code in my question. Basically now if there are validation errors, how would I get them to display on the form? I'm assuming I would return a value from my controller and then have a statement in my ajax success that if msg == "error" display the errors elseif msg == null, display success message. But how would i tell my view to display those errors based on an ajax success variable?