CSRF token for ajax
I have a problem with forms submitted with ajax. I do my forms with Zend Framework. Some are real forms so I add a Hash element. Others are for small operations (like upvote and downvote here) so I do them with links.
My problem is that I need to use ajax especially for the small forms (the links). I see a lot of questions but nothing comprehensive enough to solve the proble开发者_如何学编程m. Is there a detailed description on how to get csrf token working smoothly when forms are submitted via ajax? preferably with Zend Framework but general PHP answers will help too.
You don't need a CSRF
token. You case use the HTTP_X_REQUESTED_WITH
method (see e.g. here).
For those coming to this page, it is possible to get csrf working with ajax.
In the controller you will need to regenerate the hash using via adding this right before the end of the action:
$form->hash->initCsrfToken();
$this->view->csrfhash = $form->hash->getValue();
In the js file you're using to do the ajax, you're going to need to use a selector to find the instance of the hash as it is created (so for jquery:
$(#hash).replaceWith(csrfhash); Actually if you use replaceWith you're going to replace the entire hidden csrf element including the id and name. But that part should be fairly easy to do.
精彩评论