简体   繁体   中英

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 problem. 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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM