Search code examples
javascriptphphtmlformsnoscript

Inserting <noscript> or similar within form tag (HTML, JavaScript)


I have the following form:

<form id="signup" onsubmit="return false;">
  ... form content...
  <input class="button" type="submit" />
</form>

Where upon clicking the button, a JavaScript function signup() is called. This function uses an AJAX call to validate the form (compare to current database values), and then submit the form via a PHP function.

My question is: If the user has their JavaScript disabled in their browser, is there a way that I can modify the <form> tag to include an action and method?

Since HTML5 allows <noscript> tags within the body, I thought I'd try something like:

<form id="signup" <noscript>action="..." method="post"</noscript>>

but that doesn't work.

If the user has their JS enabled, I would like the AJAX calls to handle everything - it makes for a very clean user experience. BUT, I need it to still be functional for those people who have disabled their JS.

Thank you in advance.


Solution

  • You're looking at it the wrong way round. You always want to include the action and method attributes on your form.

    <form id="signup" action="/path/to/signup" method="post">
    

    Then you bind a function to the submit event, and prevent the form from submitting by using .preventDefault(); (I'm assuming jQuery usage here)

    $('#signup').on('submit', function(e) {
        e.preventDefault();
    
        // submit data via ajax here
    });
    

    This is much better, because you don't have to set the login URL in your javascript any more. You simply get it from the form.

    $.ajax({
      type: "POST",
      url: $('#signup').attr('action'),
      data: $('#signup').serialize()
    })
      .done(function( msg ) {
        // logged in (or not)
      });