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

Bradley James Ahrens's avatar

Submit Form within Bootstrap Modal - TokenMismatchException Error

Hey guys,

I'm creating a form inside of a bootstrap modal. Here is the form:

<form action="{{ url('/post')}}" method="POST" id="my_form">
  {{ csrf_field() }}
  <input type="text" name="Comments" id="Comments">
  <button onclick="form_submit()">Submit</button>
</form>

and here is the javascript I'm using to post it:

<script type="text/javascript">
function form_submit() {
  document.getElementById("my_form").submit();
 }
</script>

Unfortunately, when I submit, I get the following error:

(1/1) TokenMismatchException in VerifyCsrfToken.php (line 68)

I've also tried to insert a hidden field for the token:

<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />

Unfortunately, no luck.

Any idea how I can fix this?

Thanks!

0 likes
8 replies
matt_panton's avatar

The form you're selecting in your javascript is facebook_form but the one in your html has the id of my_form?

1 like
matt_panton's avatar

Okay bit of a long shot but because you're not preventing the default behaviour of the form submission in javascript, it could be that the form is submitting once when you click the button and then straight away after through javascript? perhaps try putting type="button" on the button element or

function form_submit(e) {
    e.preventDefault();
    document.getElementById("my_form").submit();
 }
1 like
Bradley James Ahrens's avatar

Good idea @matt_panton, but unfortunately, then it doesn't submit anything at all. :( Also, I don't think it would submit twice since the "submission" button doesn't have the "type='submit'" tag.

matt_panton's avatar

I just tried this code and it works for me:

<form action="" method="post" id="form">
    {{ csrf_field() }}
    <input type="text" name="name">
    <button type="button" onclick="handleSubmit()">Submit</button>
</form>


<script>
function handleSubmit () {
    document.getElementById('form').submit();
}
</script>
Cronix's avatar

Why even use javascript here? It's not doing anything except submitting the form, just the same as it would if there wasn't any javascript.

Bradley James Ahrens's avatar

@matt_panton , hmmm, that's weird. I still couldn't get it to work. It looks like our code is the same. Are you doing this within a bootstrap modal?

Please or to participate in this conversation.