I’m trying to send an value with Ajax to Controller file in Codeigniter but without success.I have searched for that problem and i now this question is made many times here,but still can’t find a sultion.Hope anyone can help me. Thanks !
Js file.
function submitSend() { var message = $('#sms').val(); if(message == "") { $("#sms").attr("placeholder", "Type a message please..."); return false; } $.ajax( { url: "<?php echo base_url();?>/mychat/send", type: 'POST', data:{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', 'message': message }, success: function (data) { window.console.log('Successful'); }, error :function(data) { window.console.log('Failed'); } }); }
Controller function.It’s in file called MyChat.
public function send() { $message = $this->input->post('message'); echo $message; }
Advertisement
Answer
Add this code in your footer view before including JS file
<?php $CI =& get_instance(); ?> <script> var csrf_name = '<?php echo $CI->security->get_csrf_token_name(); ?>'; var csrf_hash = '<?php echo $CI->security->get_csrf_hash(); ?>'; </script>
and just call these variables anywhere you need like this
data:{ csrf_name : csrf_hash, 'message': message },