Php – Is the form tag necessary

htmlPHP

In my HTML code, I have a form tag that contains two input boxes, username and password. The form submits the values to a PHP file which validates the values with the database and redirects to another page if the login is successful.

The problem with this approach is that, if AJAX is not involved, it refreshes the page even if the login is unsuccessful.

I would like to remove the form tag altogether, merge the PHP code into the same file as the HTML. For this I attempted to add an onclick() event to the input boxes. But since form tag was removed, something awkward happened. I picked the values using: document.getElementByID

I want to know whether it is necessary for an input tag to be enclosed within the form tag? If I just want the input box and want to have some operation done using the onclick event, would it work?

Best Answer

My preferred method is to leave the <form> tag but catch the onsubmit event of the form and just return false.

<form name="foo" id="foo" action="" method="post">
  <input type="text" name="bar" id="bar" />
</form>

Here's some rough PrototypeJS code that illustrates the approach.

<script type="text/javascript">
  //Handle the window onload event
  Event.observe(window, 'load', function() {

    //Handle the form submit event
    Event.observe($('foo'), 'submit', function(event) {
      //Stop the event so the form doesn't actually submit
      Event.stop(event);
    });

  });
</script>