Suresh Mali
Suresh Mali

Reputation: 27

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?

Upvotes: 0

Views: 2980

Answers (2)

Sravan
Sravan

Reputation: 18647

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

Upvotes: 1

Chung Le
Chung Le

Reputation: 95

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!

Upvotes: 1

Related Questions