I'm using a CSRF token as part of a form in my app, and I'm having a problem where it always comes back as invalid in the event that form was loaded into the page with AJAX. The relevant parts of my code are below.
Part of the controller function that displays the form:
$session = new \Session();
$f3->SESSION["token"] = $session->csrf();
unset($session);
$f3->pagecontent = "snippet/networkform.php";
$this->generatePage($f3);
Part of the controller function that receives and validates the POST data:
if ($_POST["token"] != $f3->SESSION["token"]) $f3->error(400, "Unexpected data");
$f3->clear("SESSION.token");
Part of the form itself (a view):
<input type="hidden" name="token" value="{{ @SESSION.token }}">
The private function generatePage() from the controller class:
$view = \Template::instance();
if (!$f3->AJAX) echo $view->render("page.php");
else echo $view->render($f3->pagecontent);
What the generatePage function is doing is checking to see how the page was requested. If it's an AJAX request then it renders only the relevant part of the HTML. On the client side, this is inserted into the page with jQuery, leaving all the ancillary parts of the page intact. If it was a synchronous request then the generatePage function renders a complete HTML page including the <head> section, page structure (menu bars, etc) and the content (the form, in this case) itself.
Part of the page.php view:
<include href="{{ @pagecontent }}" />
If I load the form by navigating directly to it's URL with a synchronous request then everything works great. When the form is submitted the CSRF token from the POST data is evaluated against the corresponding session variable, they match, and all is well with the world.
However, if the form content is loaded by AJAX and inserted into an existing page with jQuery, I can see by inspecting the loaded data that a CSRF token is in there, but when the form is submitted it doesn't match the stored session variable. I'm at a loss to figure out why.
To be clear, the form is not (yet) being submitted by AJAX (it will be eventually, but I'm still building). When the user hits submit it's a synchronous POST request to the form handler route, regardless of how the form was loaded.
Any idea what I'm doing wrong?