2

Is there any way to preserve the default behavior of a form POST submit action in a javascript http request? Normally when I submit the forms, the url is redirected to the action and the page is replaced with the response html, but if you use preventDefault() or return false on a submit event you will get the response in HTML sent as a string to the callback.

Right now I have to add some extra data to my form submission, but I would like to update the page based on the response.

  $("#"+target).on('submit', function (e)

    const counselors_list = counselors.list.map(e=>e.name);
    const groups_list = ...
    const data = $(this).serialize() + "&" + $.param({patient: {counselors: counselors_list, groups_attended: groups_list}});

    $.post(action, data, e=>e)//Data gets returned as e, instead of updating the page 

    return false;
  });

The only way I can think of is replacing the whole DOM with the response, but that seems very hacky. Is there any way to preserve the default form behavior while still adding this data?

trognanders
  • 2,113
  • 21
  • 31
occurr
  • 21
  • 2
  • Yes, normally you update the DOM elements yourself after a ajax success. – Spencer Wieczorek Mar 20 '17 at 02:18
  • 2
    You don't have to use Ajax. In your submit handler you can just put the extra data in hidden input fields, then *don't* cancel the default submit behaviour. The form will submit as normal, *with* your extra data, and then the browser will display the returned page by default. – nnnnnn Mar 20 '17 at 02:18
  • I would use hidden fields if I could but sadly it is not practical for this use case. – Burdock Mar 20 '17 at 02:20
  • Well you could use one hidden field that contains a JSON representation of all of the extra data (value set at the time of submit), then parse the JSON server-side. That would be very simple to implement at both ends. But basically if you *do* use Ajax then you will have to update the DOM from JS, bearing in mind that replacing the *whole* DOM would mean having to bind event handlers again, if you have any bound to elements getting replaced. – nnnnnn Mar 20 '17 at 02:24
  • 1
    Use javascript to create a new form, populate it with hidden fields full of your data, then submit. There's an example in [this answer](http://stackoverflow.com/a/133997/149097). – Robert Mar 20 '17 at 02:25

0 Answers0