Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

octoxan's avatar

TokenMismatchException on submitting a form that didn't exist on page load.

Not sure what is going on here.

I have a form that is ajax'd into the page, it does not exist on page load.

When I submit this form, I get the TokenMismatchException error.

If I place the exact same form directly on the page, not ajax'd in, the form works perfectly fine.

I have a the hidden _token field with the correct value in it. It is being sent in the header according to Dev Tools.

Is it not possible to create a form with ajax and then submit it in Laravel, or is there some trick?

0 likes
5 replies
octoxan's avatar

@jlrdw No, I am not trying to ajax submit a form. I'm trying to submit a form that has been loaded onto the page via ajax.

jlrdw's avatar

Again search, been answered 500 times

octoxan's avatar

@jlrdw You apparently don't understand what it is I'm asking since you linked to a completely unrelated question.

My form did not exist when the page loaded. I'm not trying to AJAX submit anything! I'm trying to submit just a regular form, with a submit button. But the form did not exist until an ajax call loaded in the form.

The form contains the _token in a hidden field.

octoxan's avatar
octoxan
OP
Best Answer
Level 3

Figured it out.

I was developing and using browsersync so I was on localhost.

When the form is ajax loaded onto the page, the action was no longer pointing to localhost, it was pointing to the Laravel site url.

{!! Form::open(['method' => 'POST', 'action' => ['ExportsController@report']]) !!}

will spit out...

<form method="POST" action="//localhost:3000/exports/report" accept-charset="UTF-8">

...when I call the form directly in the view. But when I ajax in this form, it becomes...

<form method="POST" action="//example.com/exports/report" accept-charset="UTF-8">

This is happening even though I'm ajax loading the form onto the page with a relative url, never calling example.com directly.

No idea why this is, but that fixed my issue sort of, as it's only an issue when browsing on localhost.

Please or to participate in this conversation.