Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form and stay on same page?

I have a form that looks like this

<form action="receiver.pl" method="post">   <input name="signed" type="checkbox">   <input value="Save" type="submit"> </form> 

and I would like to stay on the same page, when Submit is clicked, but still have receiver.pl executed.

How should that be done?

like image 543
Sandra Schlichting Avatar asked Apr 20 '11 16:04

Sandra Schlichting


People also ask

How do you stay in the same page after submit a form in HTML?

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

How do I submit a form to the same page?

In order to stay on the same page on submit you can leave action empty ( action="" ) into the form tag, or leave it out altogether. For the message, create a variable ( $message = "Success! You entered: ". $input;" ) and then echo the variable at the place in the page where you want the message to appear with <?


2 Answers

99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

<style>   .hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; } </style>  <iframe name="hiddenFrame" class="hide"></iframe>  <form action="receiver.pl" method="post" target="hiddenFrame">   <input name="signed" type="checkbox">   <input value="Save" type="submit"> </form> 

There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...

  • gracefully handle errors (e.g. retry)
  • provide UI indicators (e.g. loading, processing, success, failure)
  • run logic before the request is sent, or run logic after the response is received.
like image 149
jessegavin Avatar answered Sep 28 '22 06:09

jessegavin


The easiest answer: jQuery. Do something like this:

$(document).ready(function(){    var $form = $('form');    $form.submit(function(){       $.post($(this).attr('action'), $(this).serialize(), function(response){             // do something here on success       },'json');       return false;    }); }); 

If you want to add content dynamically and still need it to work, and also with more than one form, you can do this:

   $('form').live('submit', function(){       $.post($(this).attr('action'), $(this).serialize(), function(response){             // do something here on success       },'json');       return false;    }); 
like image 44
Herman Schaaf Avatar answered Sep 28 '22 06:09

Herman Schaaf