I am trying to use the Backbone.js models to save Yii in my web application, but I get the answer โCSRF Token Validation cannot be verifiedโ even if the model is a serialized form and I use Backbone.sync to set the title.
Model (the form has a CSRF token in it and sends it as the attribute "YII_CSRF_TOKEN"):
var v = new ModelName ($('.formclass').serializeJSON());
JSON Serializer:
//form.serializeJSON (function( $ ){ $.fn.serializeJSON=function() { var json = {}; jQuery.map($(this).serializeArray(), function(n, i){ json[n['name']] = n['value']; }); return json; }; })( jQuery );
Backbone.sync:
Backbone.old_sync = Backbone.sync; Backbone.sync = function(method, model, options) { var new_options = _.extend({ beforeSend: function(xhr) { console.log('backbone sync'); var token = model.get('X_CSRF_TOKEN'); console.log('token ='+token) if (token) xhr.setRequestHeader('YII_CSRF_TOKEN', token); } }, options) Backbone.old_sync(method, model, new_options); };
I also tried setting the header as "X_CSRF_TOKEN", but to no avail.
source share