php - CSRF Protections with AJAX & FORM - CodeIgniter - Not Sending

812

In the beginning I turned off my CSRF just for simplicity reasons to make my form / ajax work. Now when I turned it on and tried to use the inputs and stuff for CSRF nothing will work. My form doesn't submit or when It does my whole page refreshes which I can't let that happen. Here is my current code.

form method="post">
  <input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br><br>
  <input type="submit" id="submit" value="Redeem" onclick="return rebate_amount()">
  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
</form>

And the AJAX:

function rebate_amount(){

  var value = document.getElementById('vip').value;
  var datastring = 'vip='+value;
  var url = base_url + '/index.php/home/redeeming_form_value';

  $.ajax({
    type : 'post',
    url : url,
    data: datastring,
    cache: false,
    success: function(html){

      $('#vip_point_redeeming').html(html);

    }
  });
  return false;
}

Keep in mind. This all works when CSRF is off in the config file. But I think theres a problem here with CSRF with form / ajax.

478

Answer

Solution:

You should also includecsrf_token with data

500 internal server error

Your AJAX request constructs a POST operation but fails to provide the CSRF token. When CodeIgniter receives the POST operation, it fails to find the TOKEN and shuts everything down before you have a chance to run any code, thus you receive 500 internal server error

Either you make

data :  $("#your_form").serialize();

OR

data: {
        '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',

           /*....your data....*/
           vip:document.getElementById('vip').value
       },

Your function would look somewhat

function rebate_amount(){

var url = base_url + '/index.php/home/redeeming_form_value';

$.ajax({
    type : 'post',
    url : url,
    data: {
    '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',

       /*....your data....*/
       vip:document.getElementById('vip').value
    },
    cache: false,
    success: function(html){
      $('#vip_point_redeeming').html(html);
    }
  });
  return false;
}

People are also looking for solutions to the problem: php - JQUERY autocomplete not refreshing data from mysql database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.