Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

generate validate token for ajax request

posted by shakeel 8 years ago

I have a form with ajax submit and add the record . i used geerate token . i also send it with ajax request . first time its working fine after that token validation is not working. please tell me how to use token for ajax request.

I would probably generate a new token and return it in the ajax response to use for the next request.

posted by wbond 8 years ago

In your response, put a new CSRF to replace the old one. IMO, this is easier done with JSON as the response format.

// jQuery example
$('#some-form-element').submit(function () { // <form id="some-form-element">
  var $csrf = $(this).find('[name="csrf"]'); // example: <input type="hidden" name="csrf" value="joeiahgioejh">
  var $form = $(this); // store reference so we can refer to it in the callbacks
 
  // Do things like disable submit button or the whole form if you wish
 
  $.post('/some-place-to-post', {csrf: $csrf.val()}, function (json) {
    if (json.csrf !== 'undefined') {
      $csrf.val(json.csrf); // Replace old
    }
 
    // Do things like re-enable the submit button
    // Empty the form, swap page state, etc
    // You can use $form to refer to the form
 
    return false; // prevent 'real' submit action (as in doing a normal POST)
  }, 'json').error(function () { $form.append($('<span/>').addClass('error').html('An error occurred.')); });
});
// Page response
$csrf = fRequest::get('csrf', 'string');
$data = array();
if (fRequest::validateCSRFToken($csrf)) {
  $data['csrf'] = fRequest::generateCSRFToken();

  // Do form processing

  // Send the response; exit here if you have code otherwise that would generate a page after this
  fJSON::sendHeader();
  print fJSON::encode($data); // If the above failed, {} is what the Javascript will get back so at least $.post with 'json' as response type won't complain, but it won't have a valid CSRF
  exit;
}

header('HTTP/1.1 404 Not Found'); // Force the .error() callback if the CSRF didn't validate
exit;
posted by audvare 8 years ago