gelviis
gelviis

Reputation: 458

How to force comma in URL using Codeigniter, Javascript and GET form

I want a URL using Codeigniter that is like this:

example?type=1,2,3,4

I can manually type this in and also navigate to URLs like this and the system works OK. However, I have a form using GET where I want to post multiple values for type. I'm using Javascript to join the inputs.

<form action="example" method="GET" id="type-form">
    <select multiple="multiple" name="_type[]" id="type-array-id-1">
        <option value="1">Type 1</option>
        <option value="2">Type 2</option>
        <option value="3">Type 3</option>
        <option value="4">Type 4</option>
        <option value="5">Type 5</option>
    </select>
    <input type="hidden" name="type" id="type-comma-sep"/>
    <input type="submit" value="Get" />
</form>
<script>
    $("#type-form").bind("submit",function(){
        var type_array = $("#type-array-id-1").val().join(",");
        $("#type-array-id-1").val("");
        $("#type-comma-sep").val(type_array);
    });
</script>

I've used some other SO questions answers to get me this far BUT when I submit the form I get:

example?type=1%2C2%2C3%2C4

My back-end relies on the "," being present in the URL. So how can I force the comma into the URL?

I also tried htaccess rewrite (although not even sure this is right):

RewriteCond %{REQUEST_URI} ^([^\%2C]*)\%2C(.*)$
RewriteRule .* %1,%2 [R=301,L]

And I tried using encodeURIComponent(type_array) and encodeURI(type_array), but it never made a difference.

Also my settings in Codeigniter are as follows:

$config['permitted_uri_chars'] = 'a-z 0-9~%.,:_\-';

And within system/libraries/input.php

if ( ! preg_match('/^[a-z0-9,:_\/-]+$/i', $str))

So...

  1. How can I force the comma in the URL (Javascript is preferable)?
  2. Will the solution work cross-browser?

Upvotes: 1

Views: 1742

Answers (1)

manavo
manavo

Reputation: 1899

If you do the redirect via Javascript then it should be OK!

$("#type-form").bind("submit",function(){
    var type_array = $("#type-array-id-1").val().join(",");

    window.location = '?type='+type_array;

    return false;
});

If you let the form submit normally, it'll URL encode all the query string parameters, converting your commas.

If you just explicitly set the URL with the commas, it should work OK (or at least it did in my test example above)!

Upvotes: 1

Related Questions