Get the URL generated from a form on submit with JavaScript
Asked Answered
D

5

22

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!

Dire answered 4/2, 2015 at 23:32 Comment(1)
You can get the form's action attribute. If no action attribute is defined, then the current page is the target.Rimini
S
4

To put it simply, you can't. The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:

name=value&name2=value2
Sag answered 4/2, 2015 at 23:52 Comment(4)
I don't want it simple, I know I can get them from field as usual, please elaborate sirDire
You can not intercept the request that form will send to the server.Sag
Hello from the future, where it is possible to intercept HTTP requests in JavaScript.Salad
@Salad the only way I can think of for regular pages is via service workers - a very convoluted way at that. But thank you!Sag
S
22

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!

Salad answered 29/7, 2019 at 8:50 Comment(2)
Some browser compat issues with URLSearchParams, lovely solution though!Waftage
Perfect, the more you use JavaScript the more you learn that there are still lots of things you need to learn.Incipit
M
5

If you mean getting the form's action URL, that URL can be retrieved like this:

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

If you are using jQuery and assuming you are doing an Ajax request, it would be like this:

var el = $('#form-id');
$.ajax({
    type: el.attr('method'),
    url: el.attr('action'),
    data: el.serialize(),
    context: this
}).done(callback);
Molality answered 4/2, 2015 at 23:42 Comment(2)
Nope, I'm talking about the generated serialized URL data which gets constructed on submission, the [email protected]&name=myname ... part!Dire
sorry buddy, don't yet have the privileges to comment and seek clarification, so posted this as an answer, thought that might've been what you are asking.Molality
S
4

To put it simply, you can't. The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:

name=value&name2=value2
Sag answered 4/2, 2015 at 23:52 Comment(4)
I don't want it simple, I know I can get them from field as usual, please elaborate sirDire
You can not intercept the request that form will send to the server.Sag
Hello from the future, where it is possible to intercept HTTP requests in JavaScript.Salad
@Salad the only way I can think of for regular pages is via service workers - a very convoluted way at that. But thank you!Sag
S
4

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

If you are using jQuery then use serialize(). If not, refer to the post Getting all form values by 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>
Scrimpy answered 16/8, 2017 at 10:23 Comment(0)
S
0

You can use javascript to generate it:

<script>
function test(frm) {
  var elements = frm.elements;
  var url = "?";
  for(var i=0;i<elements.length;i++) {
    var element = elements[i];
    if (i > 0) url += "&";
    url += element.name;
    url += "=";
    if (element.getAttribute("type") == "checkbox") {
      url += element.checked;
    } else {
      url += element.value;
    }
  }
  console.log(url);
  return false;
}
</script>

<form onsubmit='return test(this);'>
<input name=field1 value='123'>
<input type=checkbox name=field2 checked>

<input type=submit>
</form>
Span answered 17/10, 2020 at 1:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.