forbidden in ajax call error function in codeigniter csrf

♀尐吖头ヾ 提交于 2019-12-12 02:14:07

问题


I'm just getting started with codeigniter I want to insert some data into database via ajax but I have a problem with my ajax call; I've been searching for two hours but I could not solve the problem. My problem is when I click on submit button it says forbidden.
Also my csrf protection is set to TRUE! Please help, thanks

JS

$(document).ready(function() {

$(".addbtn").click(function (e) {
        e.preventDefault();
        if($("#mname").val()==='' || 
           $('#sname').val() === '' || 
           $('#genre').val()==='' || 
           $('#album').val()==='' ||
           $('#publishyear').val() ==='' ||
           $('#artist').val()==='')
        {
            alert("Please fill all the fields!");
            return false;
        }

        $("#FormSubmit").hide(); 
        $("#LoadingImage").show(); 

        var baseurl = "<?php echo base_url(); ?>";
        var data = {
                'mname': $("#mname").val(),
                'sname': $('#sname').val(),
                'genre': $('#genre').val(),
                'album': $('#album').val(),
                'publishyear': $('#publishyear').val(),
                'artist': $('#artist').val(),
                '<?php echo $this->security->get_csrf_token_name(); ?>':
                '<?php echo $this->security->get_csrf_hash(); ?>'
                };

        $.ajax({
        type: "POST", 
        url:  baseurl+"index.php/admin_page/send_ajax", 
        data: data, 
        success:function(){
            alert("success");

        },
        error:function (xhr, ajaxOptions, thrownError){
            $("#FormSubmit").show(); 
            $("#LoadingImage").hide(); 
            alert(thrownError);
        }
        });
  });});

Config file

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();

Controller

public function send_ajax(){


    $data = array(
                'name_of_music'=>$this->input->post("mname", TRUE),
                'artist'=>$this->input->post("artist", TRUE),
                'name_of_singer'=>$this->input->post("sname", TRUE),
                'genre'=>$this->input->post("genre", TRUE),
                'album'=>$this->input->post("album", TRUE),
                'publishyear'=>$this->input->post("publishyear", TRUE)
            );
    $json_data['lyrics_info_data'] = json_decode($data);
    $this->user_model->insert_json_in_db($json_data);
  }

Model

public function insert_json_in_db($json_data){
    $this->db->insert('lyrics', $json_data);
  }

回答1:


Can you confirm what is the use of this line $json_data['lyrics_info_data'] = json_decode($data); ? I think error is with this line.

You may use $json_data['lyrics_info_data'] = $data; instead of $json_data['lyrics_info_data'] = json_decode($data);

Also the model function need to update.

public function insert_json_in_db($json_data){
    $this->db->insert('lyrics', $json_data['lyrics_info_data']);
}

Script update

Codeigniter will regenerate its crcf token on each request and this info will be stored in cookie. So token value you need to take from cookie and send along with ajax data you are passing. What I am doing with folliwing javascript is that, using a common function to attach crcf value along with all the ajax request.

In jquery there is an option to add custom data along with ajax request. See jquery documentation http://api.jquery.com/jquery.ajaxprefilter/ for more details

<script>
   $(document).ready(function(){ 

function getCookie(c_name) { // A javascript function to get the cookie value 
    if(document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if(c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if(c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

$.ajaxPrefilter(function(options, originalOptions, jqXHR){ // This function will attach "csrf_test_name" with all the request you are sending. 
    if (options.type.toLowerCase() === "post") { // Required only if its a post method 
        var csrf_token = getCookie("csrf_test_name");
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "csrf_test_name=" + csrf_token;
    }
});
 });
   </script>

You can remove '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' from var data.

Important note: if you change $config['csrf_token_name'] = 'csrf_test_name'; in config.php then you need to update this script as well.

Please try after updating your code and let me know if issues still exists.




回答2:


Make Sure you are getting right base_url() and in javascript you should define the base_url() globally somewhere so that you can access it in any script as below

var baseurl = <?php echo base_url() ?>;

`




回答3:


You are going way out of your way to make this difficult. csrf is not your problem. Try something like this

$(function () {
 "use strict";
 $("#form2").submit(function () {
 var data = $("#form2").serialize();
 //alert(data); return false;
 $.ajax({
  url: "/log/login",
  data: data,
  type: "POST",
  success: function (msg) {
    $("#display").text(msg);
  },
  error: function (msg) {
    $("#display").text("its all bad");
  }
  });
  return false;
 });
 });

(Of course you will need to put your own form id in etc)

Your controller should look something like this:

  $data = array(
'borncity'  => htmlspecialchars(trim($this->input->post('borncity'))),
'state'     => htmlspecialchars(trim($this->input->post('state'))),
'country'   => htmlspecialchars(trim($this->input->post('country'))),
'family'    => htmlspecialchars(trim($this->input->post('family'))),
'year'      => htmlspecialchars(trim($this->input->post('year'))),
'state1'    => htmlspecialchars(trim($this->input->post('state1'))),
'deathcity' => htmlspecialchars(trim($this->input->post('deathcity')))
);

$this->form_validation->set_rules('borncity', 'city of birth', 'required|trim');
$this->form_validation->set_rules('state', 'state', 'required|trim');
$this->form_validation->set_rules('country', 'country', 'required|trim');
$this->form_validation->set_rules('family', 'family', 'required|trim');
$this->form_validation->set_rules('year', 'year', 'required|trim');
$this->form_validation->set_rules('state1', 'Born State', 'required|trim');
$this->form_validation->set_rules('deathcity', 'Death City', 'trim');

if( $this->form_validation->run() == FALSE) {
  echo validation_errors();
}else
{
  $this->db->insert('cities', $data);
  echo "Success"; //this will show up in your ajax success line
}
}

Use Codeigniter's form validation in your controller. You do not need to use json decode. Please note these are examples



来源:https://stackoverflow.com/questions/39549195/forbidden-in-ajax-call-error-function-in-codeigniter-csrf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!