Send a form without the "?" character and the name of the value

Viewed 64

I have this code:

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
    <form action="https://api.pagar.me/1/zipcodes/">
        <input type="text" placeholder="cep" name="cep">
        <input type="submit">
    </form>
</body>
</html>

When I type a number, for example 05423110, I get on the adress bar is "https://api.pagar.me/1/zipcodes/?cep=05423110", but I would like to have "https://api.pagar.me/1/zipcodes/05423110".

What do I need to change on my code?

Thanks!

2 Answers

I would do it like this. The other answer will have the problem where it could potentially append something twice.

I also set it so the button disables for user friendliness (in case the server takes awhile to respond).

This solution does use jQuery, but chances are you will need to do other simple DOM manipulation and this will be very helpful.

Because you don't want the query string in there, but you must have it be GET, then its impossible not to have it append the query string to the URL (because that's what a GET request does).

Instead, I use javascript to simply redirect to the proper URL and ignore the form GET/POST entirely.

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
    <form action="https://api.pagar.me/1/zipcodes/">
        <input type="text" placeholder="cep" name="cep">
        <input type="submit">
    </form>
</body>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  (function() {
    var form = $('form');
    var baseUrl = form.attr('action');

    $('form').submit(function(e) {
      e.preventDefault();
      form.find('[type="submit"]').prop('disabled', true);
      window.location.href = baseUrl + form.find('[name="cep"]').val();
    });
  })();
</script>

Add method="post" to the form tag, then add an event listener to the form's submit event which append the input value to the action attribute value on the form:

const form = document.forms[0]

form.addEventListener('submit',()=>{form.action+=cep.value}) 
<form action="https://api.pagar.me/1/zipcodes/" method="post">
  <input type="text" placeholder="cep" name="cep" id="cep">
  <input type="submit">
</form>

Ofc StackOverflow snippets prevents POST.

Related