how to insert from data using ajax in codeigniter?
step 1) in test.php load db
public function __construct(){ parent::__construct(); $this->load->database();}
step 2) modify
$this->db->insert('contact',$data); if($status['success']) { // code }
to
if($this->db->insert('contact',$data)){ //rest of code}
it should work
change in controller
note: please read commented line for better undersatnding
public function signin(){ if($this->input->post('insert')) { $name = trim($this->input->post('name')); $email = trim($this->input->post('email')); $phone = trim($this->input->post('phone')); $message = trim($this->input->post('message')); $s_data = date('Y-m-d'); $data = array( 'name' => $name, 'email' => $email, 'phone' => $phone, 'message' => $message, 's_date' => $s_date ); $recaptchaResponse = trim($this->input->post('g-recaptcha-response')); $userIp=$this->input->ip_address(); $secret='****************************'; $url="https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response;=".$recaptchaResponse."&remoteip;=".$userIp; $response = $this->curl->simple_get($url); $status= json_decode($response, true); if($status['success']) { //insert data when get success in google recaptcha $this->db->insert('contact',$data); $res['msg']="successfull"; //no need to set flash session in CI for ajax //$this->session->set_flashdata('flashSuccess', 'successfull'); } else { //$this->session->set_flashdata('flashSuccess', 'Sorry Google Recaptcha Unsuccessful!!'); $res['msg']="Sorry Google Recaptcha Unsuccessful!!"; } //set page header as json format $this->output ->set_content_type('application/json') ->set_output(json_encode($res)); }}
change your script
<script> $(document).ready(function(){ $("#insert").click(function(){ var name = $("#name").val(); var email = $("#email").val(); var phone = $("#phone").val(); var message = $("#message").val(); //pass object in post var dataString = {'name': name , 'email': email , 'phone': phone , 'message': message}; if(name==''||email==''||phone==''||message=='') { alert("Please Fill All Fields"); } else { // AJAX Code To Submit Form. $.ajax({ type: "POST", url: "<?php echo base_url('index.php/'); ?>test/signin", data: dataString, dataType: 'json', cache: false, success: function(result){ alert(result.msg); } }); } return false; }); });</script>
thanks