[Answered ]-How to do ajaxSetup beforeSend like stuff in DOJO toolkit to provide CSRF token in DOJO AJAX POSTs

1đź‘Ť

Disclaimer: I’m not familiar with django.

Outside of extending the base dojo xhr definition(wouldn’t recommend it), I’d say you may want to extend dojo.xhr or build a utility method.

Utility method would mix in or set the “headers” attribute of the arguments you pass into dojo.xhr :

myCustomNameSpace.xhr = function (xhrArgs) {
var csrfHeader = { “X-CSRFToken” : dojo.byId(csrfmiddlewaretoken).val(); };
xhrArgs.headers?dojo.mixin(xhrArgs.headers,csrfHeader):xhrArgs.headers=csrfHeader;
dojo.xhrPost(xhrArgs);
};

Invoked via myCustomNameSpace.xhr({method:”POST”,url:”http://www…..”});

👤Kevin

1đź‘Ť

The {% csrf_token %} will appear in the form just like this:

<input type='hidden' name='csrfmiddlewaretoken' value='...' />

so just mix your content like this:

var form = dojo.byId("postForm");
dojo.xhrPost({url:form.action,
    content:{text:form.text.value, csrfmiddlewaretoken:form.csrfmiddlewaretoken.value},
)
👤Speq

Leave a comment