Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit form with GET method and using URI template?

Tags:

rest

html

forms

I read this article http://blog.welldesignedurls.org/2007/01/11/proposing-uri-templates-for-webforms-2/ about URI Templates but it seems a dead project.

So there are anyway to submit form like this ?

<form action="/orders/{id}" method="get">
    <input type="text" name="id"/>
    <input type="submit" value="Submit"/>
</form>

The form after submiting forwards to an odd url: /orders/%7Bid%7D?id=1

like image 370
Hoan Dang Avatar asked Mar 12 '13 03:03

Hoan Dang


2 Answers

You can use the GET method, but you will get name-value pairs in the URL, and it will not pick up the template. If you type "5" into this form:

<form action="/orders" method="get">
    <input type="text" name="id"/>
    <input type="submit" value="Submit"/>
</form>

On submit, you will get the URL /orders?id=5, and not /orders/5.

If you're looking for /orders/5, it can be done easily enough with some jquery:

<script type="text/javascript" language="javascript">
$("form").submit(function () {
    // prevent the default GET form behavior (name-value pairs)
    event.preventDefault();

    // Get the action attribute
    var action = $("form").attr("action").toLowerCase();

    // For each form element found, replace {elementName} in the action attribute to build a URL from template
    var values = $("form").serialize().split("&");
    for (var i = 0; i < values.length; i++) {
        var tokens = values[i].split("=");
        action = action.replace("{" + tokens[0].toLowerCase() + "}", tokens[1]);
    }

    // Send the user off to the URL w/ template elements replaced
    window.location.href = action;
});
</script>

You would have to add some escaping possibly, and handle the condition when the template input was not available, and maybe test for some other edge cases, but the above code works in the base case with any number of template elements, and would get you to /orders/5 in the above.

like image 155
J.T. Taylor Avatar answered Nov 30 '22 06:11

J.T. Taylor


You forget to close the action attribute.

<form action="/orders/{id}" method="get">
    <input type="text" name="id"/>
    <input type="submit" value="Submit"/>
</form>

and for passing {} use the escape() function.

Example

$queryString = "/orders/{id}";
$safeQueryString = escape( $queryString );

<form action="<?=$safeQueryString?>" method="get">

Pass Form ID

$('input[type="submit"]').on('click',function(e)
{
    e.preventDefault();
    var forms = $(this).parents('form');
    var formID = forms.attr('id');

    //appending form id to form action
    var dataString = forms.serialize()+'&formID='+formID;

    forms.submit();

});
like image 39
Dipesh Parmar Avatar answered Nov 30 '22 06:11

Dipesh Parmar