Get the URL generated from the form when submitting with Javascript

I was interested to know if it is possible to catch the URL generated from the form when the 'submit' event is fired.

I know that I can generate URLs from data

I am not talking about the action form url

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

Scenario:

We have a form and a JS script that sends an ajax request to a PHP script.

I usually do this:

  • Register to submit the form.
  • Preventing Default Behavior
  • Build URLs from Data
  • Open HTTP request with constructed URL

Now I was wondering when the "submit" shooting usually (for queries without an ajax) creates a URL in a form that then uses this URL to send data to a php copy.

How can I catch this URL? No clues from the event itself, which seems to be storing it, or at least I couldn't find it.

It must be somewhere!

+9
source share
4 answers

Simply put, you cannot. The best you can do is collect the values ​​of the form fields yourself or use the jQuery.serialize () function, which returns these values ​​exactly as you expected:

 name=value&name2=value2 
+3
source

Do you want to get the url of the form? This URL can be obtained as follows:

 document.getElementById("form-id").action 

If you use jQuery and assume you are running ajax, it will be like this:

 var el = $('#form-id'); $.ajax({ type: el.attr('method'), url: el.attr('action'), data: el.serialize(), context: this }).done(callback); 
+3
source

As already mentioned, you cannot get the generated URL containing the form values ​​that the browser generates, but it is very easy to build it yourself.

If you are using jQuery, use serialize () if you are not referencing this post Retrieving all form values ​​using javascript .

 var targetForm = $('#myForm'); var urlWithParams = targetForm.attr('action') + "?" + targetForm.serialize(); alert(urlWithParams); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form action="/search/" id="myForm" method="get"> <input name="param1" type="hidden" value="1"> <input name="param2" type="hidden" value="some text"> </form> 
+2
source

This is possible and simple with the URLSearchParams and FormData .

FormData is an object representation of a form for use with the fetch API. It can be built from an existing element as follows:

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

Then follows the URLSearchParams object, which you can use to build query strings:

 let search = new URLSearchParams(formData); 

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

 let queryString = search.toString(); 

Done!

+1
source

Source: https://habr.com/ru/post/1212663/


All Articles