Question

I have a form with <input type="submit id="no-js-submit">.

If Javascript is enabled I am removing this submit-input field by $('#no-js-submit').remove(); and add the "fire-ajax"-button with

$('<button id="fire-ajax" type="button">Fire Ajax</button>').appendTo('#tk-form');.

So, if JavaScript is enabled (and if jQuery is able to remove the submit-input field) the form's values will be transfered to the server by ajax.

If JS is disabled (and therefore jQuery cannot remove the submit-input) the form's values will be submitted by the <input type="submit id="no-js-submit">.

What do you think about this solution? Is there any browser (in-)compatibility I should worry about? Furthermore, is there any best practice to this?

Was it helpful?

Solution

An easier way to do it is just build a normal form that submits the data the usual way. Without JS, this should work as advertised.

If JS is enabled, you can simply "hi-jack" the form's submit event, prevent it from happening, and do everything in JS from this point onwards. No need to replace DOM elements.

$('yourFormSelector').on('submit',function(event){

  // Prevent the form from submitting normally
  event.preventDefault();

  // Turns the form into a JS Objec
  // https://stackoverflow.com/a/1186309/575527
  var formData = $(this).serializeObject();

  // Do AJAX magic here
});

To gather the form data, this answer contains a very handy method that gathers named and enabled form inputs and turns them into a JS object. You can use this function to gather the form data and feed it to your AJAX call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top