[eluser]Alhazred[/eluser]
On my site I have a form which sends the data to a controller thru an ajax request.
That did work correctly, but it stopped to work as I activated the CSRF control in the config file.
Why does it happen? How can I use the CSRF check and the ajax request together?
This is the Ajax code inside the view, with the CSRF activated it always go into the error branch, if I deactivate the CSRF check it comes back to work.
Code:
$(document).ready(function(){
$('.ajax-loader').hide();
$('input.add').click(function() {
$('.ajax-loader').show();
var form_data = {
id: $('input#id').val(),
tipo: $('input#tipo').val(),
prezzo: $('input#prezzo').val(),
inserzionista: $('input#inserzionista').val(),
codice_sconto: $('input#codice_sconto').val()
};
$.ajax({
url: "<?php echo site_url('carrello/add/') ?>",
type: 'POST',
data: form_data,
async: false,
success: function(msg) {
$('#ajax_add_cart').html(msg);
},
error: function(xhr,textStatus, errorThrown) {
$('#ajax_add_cart').html(textStatus);
}
})
$('.ajax-loader').hide();
});
});
This is the generated form with CSFR check activated
Code:
<form action="www.mysite.com/#.html" method="post" accept-charset="utf-8" name="addcart" id="addcart">
<div >
<input type="hidden" name="csrf_test_name" value="302cb0c436a726f864dd3fc8e5a376e6" />
</div>
<input type='hidden' name='id' id='id' value='1-1354017854' />
<input type='hidden' name='inserzionista' id='inserzionista' value='1' />
<input type='hidden' name='tipo' id='tipo' value='3' />
<input type='hidden' name='prezzo' id='prezzo' value='30,18' />
<input type='hidden' name='valore' id='valore' value='30,00' />
<input type='button' name='add' id='add' class='add' value='Aggiungi al carrello' alt='1-1354017854' />
</form>
This one with CSRF deactivated
Code:
<form action="www.mysite.com/#.html" method="post" accept-charset="utf-8" name="addcart" id="addcart">
<input type='hidden' name='id' id='id' value='1-1354017854' />
<input type='hidden' name='inserzionista' id='inserzionista' value='1' />
<input type='hidden' name='tipo' id='tipo' value='3' />
<input type='hidden' name='prezzo' id='prezzo' value='30,18' />
<input type='hidden' name='valore' id='valore' value='30,00' />
<input type='button' name='add' id='add' class='add' value='Aggiungi al carrello' alt='1-1354017854' />
</form>