5

I'm on a page like http://example.com?query=value that has a form <form id="formId" method="POST">.

What's the best way to submit the form to http://example.com without the query string?

I'm currently trying:

$('#formId').submit(function(e){
    e.preventDefault();
    var url = window.location.href; 
    if (url.indexOf("?") != -1){
        $('#formId').attr('action', url.split("?")[0]);
    }
    $('#formId').submit();
});

but it doesn't seem to be working.

I prefer a javascript/jQuery solution as this pattern is common through the site

3
  • Umm what do you want? Commented Aug 29, 2016 at 23:02
  • 2
    Why don't you just set the action attribute in the HTML? In theory, it's a required attribute on <form> elements Commented Aug 29, 2016 at 23:14
  • @Phil because that would require knowledge of the page url during page initiation, which I don't have due to my templating strategy. Thus why I'm asking for a Javascript/jQuery solution, which would be easy to include on each page. Commented Aug 30, 2016 at 0:04

2 Answers 2

2

Instead of attempting to change the action on submit, how about just looking for forms without action attributes and setting them appropriately, for example

jQuery(function($) {
    $('form:not([action])').attr('action', location.pathname);
});
Sign up to request clarification or add additional context in comments.

Comments

2

For anyone else looking here, a quick and dirty solution is to set the form action attribute to "?". eg:

<form id="formId" method="POST" action="?">

This will post the request to the current url with the query string just being a single "?"

Though as this does not use javascript, it might not be the answer OP is after.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.