PHP, HTML: Submit form automatically

100,019

Solution 1

Using pure javascript instead of jQuery :

<?php
    if (isset($_GET['var']))
{?>

<script type="text/javascript">
    document.getElementById('dateForm').submit(); // SUBMIT FORM
</script>

<?php 
}
else
{
  // leave the page alone
}
?>

Solution 2

I think you want this:

<?php
if (isset($_GET['var']))
{?>

<script type="text/javascript">
document.getElementById("formid").submit(); // Here formid is the id of your form
                           ^
</script>

<?php }
else
{
  // leave the page alone
}
?>
Share:
100,019
Juicy
Author by

Juicy

Updated on July 25, 2022

Comments

  • Juicy
    Juicy almost 2 years

    I have a PHP page with an HTML form on it. If some variables are set in the URL I would like to automatically submit the form on the page.

    IE:

    if (isset($_GET['var']))
    {
      // SUBMIT FORM
    }
    else
    {
      // leave the page alone
    }
    

    EDIT:

    Here is what I have using the answer that someone provided below, but it's still not working. I would like the form to submit itself if the condition is met.

    <?php
    
    if ($r == 1)
    {
    
    echo "  
      <br>
       <form action=\"bookRoom.php\" method=\"post\" id=\"dateForm\">
        <input name=\"from\" type=\"hidden\" value=\"$fday/$fmonth/$fyear\">
        <input name=\"to\" type=\"hidden\" value=\"$tday/$tmonth/$tyear\">
        <input type=\"submit\">
       </form>
    
      <script type=\"text/javascript\">
        $('#dateForm').submit();
      </script>
    ";      
    }
    ?>
    
  • Lawrence Cherone
    Lawrence Cherone over 10 years
    native javascript would suffice, no need for jQuery
  • Reeno
    Reeno over 10 years
    Be careful, this only works with a JavaScript framework which accepts $('#formid')
  • Juicy
    Juicy over 10 years
    It seems mine doesn't accept it. I apologize for my ignorance but I know very little about javascript. How can I get a framework that supports $('#formid') ?
  • Moeed Farooqui
    Moeed Farooqui over 10 years
    @user2018084 Framework?? Buddy It is jQuery a library of javascript well I have edited my answer and converted jQuery to javascript.See my updated answer
  • Moeed Farooqui
    Moeed Farooqui over 10 years
    @user2018084 Hope this will help you
  • Adam
    Adam about 7 years
    what is meant with //leave the page alone. Is there any important code?
  • Charaf JRA
    Charaf JRA about 7 years
    @Adam that was part of his example, it's a copy past