Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing question mark from a GET form with no fields?

Tags:

html

forms

get

Example:

<form>
    <input type='submit'>
</form>

When submitted results in:

http://example.com/?

How to make it:

http://example.com/

?

[This is a very simple example of the problem, the actual form has many fields, but some are disabled at times. When all are disabled, the trailing ? appears]

like image 555
Lavi Avigdor Avatar asked Nov 21 '12 12:11

Lavi Avigdor


2 Answers

In my case I'm using window.location, not sure it's the best alternative, but it's the only one I could make it work:

$('#myform').submit(function()
{
    ... if all parameters are empty

    window.location = this.action;
    return false;
});

My real use was to convert GET parameter to real url paths, so here is the full code:

$('#myform').submit(function()
{
    var form = $(this),
        paths = [];

    // get paths
    form.find('select').each(function()
    {
        var self = $(this),
            value = self.val();

        if (value)
            paths[paths.length] = value;

        // always disable to prevent edge cases
        self.prop('disabled', true);
    });     

    if (paths.length)
        this.action += paths.join('/')+'/';

    window.location = this.action;
    return false;
});
like image 128
André Felipe Avatar answered Nov 19 '22 01:11

André Felipe


Without using Javascript, I'm not sure there is one. One way to alleviate the problem may be to create a hidden input that just holds some junk value that you can ignore on the other side like this:

<input type="hidden" name="foo" value="bar" />

That way you will never have an empty GET request.

like image 1
Brendon Dugan Avatar answered Nov 19 '22 01:11

Brendon Dugan