Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the URL generated from a form on submit with JavaScript

Is it possible to catch the URL generated from a form when firing its 'submit' event?

I know I can generate the URL from data

I'm not talking about form's action URL

I mean the ?field=value&other-input-name=value& ... part

Scenario:

We have a form and a JavaScript script which sends an Ajax request to a PHP script.

I usually do like this:

  • Register for the form's submit event
  • Prevent the default behavior
  • Construct a URL from data
  • Open an HTTP request with the constructed URL

Now, I was wondering, when firing 'submit' normally (on non-Ajax requests) the URL gets constructed by the form, which then uses that URL to send data to the PHP counterpart.

How can I 'catch' that URL? There aren't any clues from the event itself which doesn't seem to store it, or at least I haven't been able to find it.

It must be somewhere!

like image 511
vinzdef Avatar asked Feb 04 '15 23:02

vinzdef


1 Answers

This is possible and easy with the objects URLSearchParams and FormData.

FormData is an object representation of a form, for using with the fetch API. It can be constructed from an existing element like this:

let form = document.forms[0];
let formData = new FormData(form);

Then comes the URLSearchParams object, which can be used to build up query strings:

let search = new URLSearchParams(formData);

and now all you need to do is call the toString function on the search object:

let queryString = search.toString();

Done!

like image 50
Greg Avatar answered Oct 13 '22 18:10

Greg