Search code examples
phpjqueryformsself-reference

Validating PHP $_POST after query form submission


What is the best way to ensure that a logic test on a self-referencing PHP form correctly identifies the HTML button used to submit the form, when that form is actually submitted via jquery.submit() -rather than by a click of the button itself?

<!DOCTYPE html>
<html>

  <head>
      <meta charset="utf-8">
       <title> Total Tutor </title>
        <link type="text/css" rel="stylesheet" href="course.css"> 
          <script src="../jquery.js"></script>

  </head>
  <body>

   <script>
     $(document).ready(function() {

     //event that triggers the javascript/jquery form submission

     $('li').dblclick(function() 
            {
                selectedCourse=$(this).text();
                  sessionStorage.removeItem('selectedCourse');
                    sessionStorage.setItem('selectedCourse', selectedCourse);
                     editForm(); 
            });

      //the function called by the normal button submission and the alternative jQuery only submission: note the non jQuery one sets the $-POST variable fine

     function editForm() {

                     var s= confirm( 'Would you like to edit ' +selectedCourse+ '');

                      if(s)
                          {
                         alert('form is called');   
                          } 
                     }

      $('#edit-button').click(function() { editForm(); });

         });

         </script> 

    <?php 
        if(!isset($_POST['submit']))
        {
     ?>

      <ul>
         <li>Maths</li>
         <li>English</li>
      </ul>

      <form  id="edit_delete" method="POST" action=" <?php echo $_SERVER['PHP_SELF']; ?>">
             <button type="submit"  id="edit-button"  name="submit"  value="edit"    ><img  src="../images/pencil.png"></button>
              <button  type="submit" id="delete-button"  name="submit" value="delete"  ><img src="../images/deleteo.png"></button>
       </form>

       }

      <?php 
        else
        {
           if($_POST['submit']=='edit')
            {
             ?>
                <p>Thank you for selecting edit</p>
           <?php
            }

           if($_POST['submit']=='delete')
            {
             ?>
                <p>Thank you for selecting delete</p>
           <?php
            }

        }
       ?>
 </body>
</html>

Solution

  • Use a variable to indicate how the data was posted.

    In your html form:

    <input type="hidden" name="wasClicked" id="wasClicked" value="1" />
    

    In your jQuery:

    $('#wasClicked').val("0");
    

    Then in your PHP, test $_POST['wasClicked'] to see if it is 0 or 1