0

I have a quite complicated HTML form. This form sends a GET request to the server. On submit event I would like to catch this GET URL and send it like an ajax request. But don't know how to get this submit URL.

I would like to have it in pure JavaScript and not with jQuery. I tried to do it via:

addEventlistener('beforeunload', function(e) {
    e.preventDefault();
    var getUrl = location.href;
});

The problem with this code is that it is not triggered by form submit, and I don't know if location.href is a good idea.

How could it be done?

Čamo
  • 3,863
  • 13
  • 62
  • 114
  • `beforeunload` event is not the best idea in this case since it is not very reliable + has its own can of worms (like inconsistently resulting in a "do you really want to leave?" prompt if you call `preventDefault` in the listener). Using `action` to find the URL suggested by Barmar is not a bad idea - if you want to get the form values, you can construct the `FormData` at the end of the `submit` listener. – Oleg Valter is with Ukraine Jul 27 '21 at 12:36
  • Instantiating the `FormData` class with the target form passed into constructor will trigger a `formdata` event on the form, which you can register a listener for and access the keys/values via the `formData` property on the event that's passed to the listener. For examples, you can take a look at [this MDN guide](https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#using_a_formdata_event) – Oleg Valter is with Ukraine Jul 27 '21 at 12:37
  • Another very good solution is listed here: https://stackoverflow.com/questions/28333613/get-the-url-generated-from-a-form-on-submit-with-javascript – AdamJones Nov 02 '22 at 17:08

1 Answers1

1

Use an event listener on the form's submit event.

document.querySelector("#yourform").addEventListener('submit', function(e) {
  e.preventDefault(); // block the default GET request
  let url = this.action;
  // rest of code for sending AJAX request to url
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    No this.action is not enough. It does not contain input values. – Čamo Jul 27 '21 at 08:23
  • That's part of the `// rest of code for sending AJAX request` – Barmar Jul 27 '21 at 14:13
  • There are many tutorials on putting input fields in AJAX requests. I was only focusing on linking the code to the submit action, to fix what you wrote. – Barmar Jul 27 '21 at 14:15
  • I dont want iterate over the form inputs if it is not necessary. I would like to get it from get request. – Čamo Jul 27 '21 at 15:09
  • 1
    There is no get request, we're preventing that. By the time the GET request happens, it's too late to intercept. – Barmar Jul 27 '21 at 15:10