I am learning AJAX and have borrowed a script from NETTUTS Codeigniter from Scratch: AJAX
The script itself works perfectly as adapted to my form, however it is not updating the database per the controller. Firebug says the post went fine from the AJAX script. I guess my question is, how and where am I failing to start the controller?
The form_open script
echo form_open('contacts/entry', $form);
Ajax script(there is validation script above what I am showing that works fine)
var form_data = {
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
phone: $('#phone').val(),
relate: $('#relate').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('contacts/entry'); ?>",
type: 'POST',
data: 'form_data',
success: function() {
$('#status').text('Update successful!');
}
});
return false;
});
Note that I have included “AJAX: 1” in the form_data
The controller
function entry()
{
if ($this->input->post('ajax')) {
$data = array
(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'relate' => $this->input->post('relate'),
);
//removed validation set rules to shorten the question
if ($this->form_validation->run() == TRUE)
{
$this->db->insert('contacts', $data);
$this->index();
} else
{
$this->index();
}
}
}
Is the use of “if ($this->input->post(‘ajax’))” the right way to initiate the controller? Without the jquery the form works fine by itself and does run the controller. So I know the two individual pieces work, they just are not meshing. Thanks
First of all I’ll delete the
var form_data { ajax: '1' }and use something like this:A nice way to handle this if is to use a MY_Controller. If you use it, add a function like this:
And you can use:
Then you’ve to echo the results to pass it to the actual view and handle the operation. Like this:
And you’ve to correct you jQuery code to handle the operation: