最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax request with codeigniter 403 (forbidden) - Stack Overflow

programmeradmin1浏览0评论

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;
  }

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;
  }
Share Improve this question asked Mar 5, 2018 at 0:31 Armand RexhmatiArmand Rexhmati 31 silver badge6 bronze badges 5
  • And all you get is a 403? What error message is shown? – Alex Commented Mar 5, 2018 at 1:28
  • You might check my related answer on this through this link – lothux1987 Commented Mar 5, 2018 at 7:31
  • @Alex now is not showing error,but when i try 'echo $message in controller file nothing is showing.Message variable is not passing to controller file. – Armand Rexhmati Commented Mar 5, 2018 at 12:53
  • @lothux1987 I have seen your answer ,my js code is ok now,but the variable message is not passing to controller file.I don't know why ! – Armand Rexhmati Commented Mar 5, 2018 at 12:54
  • check devtools to see what is getting posted. – Alex Commented Mar 5, 2018 at 17:50
Add a ment  | 

6 Answers 6

Reset to default 4

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
},

I'm afraid you can't use PHP tags in JavaScript files, as you've mentioned you have a JS file.

You must run your PHP codes in .php files.

Perhaps you can decouple your submitSend() function a bit and make it more modular by extracting the PHP tags as well as $('#sms').val(). These can be passed to the function as parameters from where you call it (.php files).

Most probably its because of the CSRF token try disable csrf and check if its due to csrf then do whitelist the specific function in csrf config

This work for me.

/app/Config/Security.php

/**
     * --------------------------------------------------------------------------
     * CSRF Token Name
     * --------------------------------------------------------------------------
     *
     * Token name for Cross Site Request Forgery protection cookie.
     *
     * @var string
     */
    public $tokenName = 'csrf_token_name';

Inside my form

<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />

in the script.js

var tokenHash=jQuery("input[name=csrf_token_name]").val();
$.ajax({
  method: "POST",
  url: "/somecontroller",
  data: { name: "John", location: "Boston" },
beforeSend: function (xhr) 
        {       
        xhr.setRequestHeader('X-CSRF-Token' , tokenHash);       
        },
})
  .done(function( msg ) {
    console.log( "Data Saved: " + msg );
  });
    

For Codeigniter 4

First, go to app/Config/Security.php

change

public $regenerate = true;

To

public $regenerate = false;

Note: Changing $regenerate to false is not good practice.

Second, go to app/Config/Routes.php create your rout that you will call to preform request.

$routes->post('url', 'ControllerName::FunctionName');

Then make sure u added csrf_token() and csrf_hash() to data you want to send.

So the code will look like this:

var data= {
    "<?= csrf_token() ?>" : "<?= csrf_hash() ?>",// make sure this line exists
    something: "Something"
};

$.ajax({
        url: "<?= base_url('url_in_routes') ?>",
        type: "POST",
        data: data,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
            
        success: function (response){
            console.log("success");
                
        },
        error: function(xhr, status, error) {
            console.log("Error: " + error);
              
        },
        plete: function(data) {
            console.log(data.statusText);
        }
});

Controller:

class Test extends BaseController{
    
    public function handleAjaxRequest(){
        $something = $this->request->getPost('something');
        // Now u can use $something to save it to ur DB or do what you want.
    }
    
}

Other thing in Codeigniter is that when a request fails the CSRF validation check, it will redirect to the previous page by default so the user can not see the error to turn it off, go to app/Config/Security.php

change

 public $redirect = true;

to

 public $redirect = false;

You can't use php tag in js file

url: "<?php echo base_url();?>/mychat/send", //this line in js file is wrong

You only use php tag in script tag in .php file like this

<script>
 // ... some code here 
     url: "<?php echo base_url();?>/mychat/send",
 // ... some code here
</script>

Or add this line in header html

<script> 
    var BASE_URL = '<?php echo base_url(); ?>';
</script>

and use it in js file

....
url: BASE_URL+"mychat/send",
....
发布评论

评论列表(0)

  1. 暂无评论