Welcome Guest, Not a member yet? Register   Sign In
How to use POST while keeping CSRF as true
#1

(This post was last modified: 12-28-2017, 07:17 AM by ciadmin. Edit Reason: Added code tags )

Hi,


I am using Codeigniter 3.1.1. And I want to submit the form using AJAX with CSRF protection enabled.
So, I have set $config['csrf_protection'] = TRUE in config.php. But the POST request does not work and gives error as 'Forbidden' as I set the CSRF variable as TRUE.

Can anybody help how can I use POST request while keeping $config['csrf_protection'] as TRUE.

Below is the PHP code for reference:
Code:
<?php

$attributes = array(

'role' => 'form', 

'id' => 'country_actvity_search'

);

echo form_open('', $attributes);

?>

<div class="row">

<div class="col-md-4">

<div class="form-group">

<?php

echo form_label('Select Country:', 'country_name');

$data= array(

'class' => 'form-control',

'id' => 'country_name',

'name' => 'country_name'

);



foreach ($country_overview as $res){

$options[$res->Country] = $res->Country;

};

echo form_dropdown($data, $options );

?>

</div>

</div>

<div class="col-md-4">

<div class="form-group">

<?php

echo form_label('Select Year:', 'country_year');

$data= array(

'class' => 'form-control',

'id' => 'country_year',

'name' => 'country_year'

);



$year = array(

'2017' => '2017'

);

echo form_dropdown($data, $year );

?>

</div>

</div>

</div>

<?php

$data = array(

'type' => 'submit',

'value'=> 'Search',

'class'=> 'btn btn-primary',

'name'=> 'Search'

);

echo form_submit($data); 



echo form_close();
?>


Below is the AJAX code for reference:
Code:
$(document).ready(function(){

$("#country_actvity_search").submit(function(e){   

e.preventDefault();

var country_name = $("select#country_name option").filter(":selected").val();

var country_year = $("select#country_year option").filter(":selected").val();

var url = "<?php echo base_url(); ?>user/country_actvity_search/";

var csrf_hash = "<?php echo $this->security->get_csrf_hash(); ?>";

$.ajax({

url: url,

method: 'POST',

data: { csrf_token_name : csrf_hash, country_name: country_name, country_year: country_year,  },

success:function(res)

{



$("#charts_country_report").html(res);





},

error: function (jqXHR, textStatus, errorThrown){

alert(errorThrown);

}

});

});
});

Thanks,
-Krati
Reply


Messages In This Thread
How to use POST while keeping CSRF as true - by kratisalgia - 12-28-2017, 06:09 AM



Theme © iAndrew 2016 - Forum software by © MyBB