简体   繁体   中英

Auto submitting form on page load

I am trying to submit a form on page load.

<?php if($abc == $xyz){ ?>
<form action="register.php" id="testform">
...form content...
</form>
<?php }  else{ ?>
Error
<?php } ?>

<script type="text/javascript">
window.onload = function(){
document.getElementById('testform').submit();
};
</script>

Auto submitting the form works fine, but it is rechecking the condition <?php if($abc = $xyz){ ?> while submitting. How to stop it from performing the same action again?

When you use document.getElementById('testform').submit(); The page will be reload again that why it rechecking condition To avoid page reload you can use ajax submit data to register.php action. Example Ajax with Jquery

$.ajax({
  method: "POST",
  url: "register.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

Hope it help!

If you can use Jquery, here is an answer with jquery .

The this one is using the jquery post request, but ignoring the response.

window.onload = function(){
    $.post('server.php', $('#testform').serialize())
};

This one is using the jquery post request, but working with response.

window.onload = function(){

    var url = "register.php"; 

    $.ajax({
           type: "POST",
           url: url,
           data: $("#testform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data);
           }
         });

    return false; // avoid to execute the actual submit of the form.
}); 

Complete reference of jquery form submit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM