0

Checkout this HTML using the attribute action, method and target from <form></form> tag:

<form action="/action_page.php" method="get" target="_blank">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <button type="submit"></button>
</form>

Is a good practice using form tag's atributes in HTML? It will redirect the user to another page. Isn't a better option always using XHR Requests?

JavaScript XHR example in JQuery with previous HTML code:

  $("button").click(function(e){
    e.preventDefault();

    $.post("demo_test_post.asp",
    {
      name: $("[name='fname']")
    },
    function(data,status){
    });
  });
3
  • I'm not a jQuery expert, so I can't speak to idioms there. But, in general, I think you'll find that form elements are often used to collect XHR parameters. Do you have a specific concern with doing this?
    – svidgen
    Sep 10, 2021 at 0:03
  • It's not good or bad practice, it's simply another way to submit data. Totally depends on your web framework and what you're comfortable with.
    – Dan Wilson
    Sep 10, 2021 at 0:57
  • 1
    In software engineering there's very very few things that are always better to use no matter the scenario. XHR has become the facto standard to send request to servers but this is due to a trend or fashion. So basically to use one or another way is a matter of convenience and adecuacy.
    – Laiv
    Sep 10, 2021 at 9:14

1 Answer 1

4

It's a technique that is used to allow websites to degrade gracefully if for some reason a browser doesn't have JavaScript turned on, or it is incompatible and the JavaScript engine crashes.

These days, between React, Angular, and several other frameworks that help build up the UI from formatted API calls (i.e. JSON, XML, etc.) and the world coming together around real web standards, the need to degrade gracefully is less important.

I will say that if there is no effective difference to the way the normal form action tag works, all you are doing is adding complexity for no gain. If you are packing that into a JSON object to POST or PUT to an API, then the JavaScript is necessary.

The example you posted is much more concisely and clearly covered by the stock behavior of the HTML elements. The JavaScript there isn't really performing any value, unless you are also going to perform validation and error handling without leaving the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.