phpjqueryajaxcodeigniterhistory.js

What's the best way to serialize an array and pass it through the get method


So I'm using an ajax request to pass some data for filtering purposes.

Then I use history.js so I can change the url and add a state to the browser, making it possible to go back, go forward etc. This way, I can filter my data with an ajax request or a normal request. So far so good.

My problem is, in the data I pass through the ajax request there is an array:

function updateContent(url, state) {
    $.ajax({
        type: 'GET',
        data: {name: state.filter_name, num: state.filter_number, 
            data: state.filter_data, array: state.filter_array},
        url: url,
        success: function(msg) {
                $('#ajax').html(msg);
        }
    }); 
    
}

This will make a request to this URL:

http: //localhost/Project/Controller/?filter_array%5B%5D=1&filter_array%5B%5D=50&filter_array%5B%5D=70.

And I want to pass this url to the history.pushstate

If I use jsenconde then build manually the url, the url will be slighter different, will be something like:

http://localhost/Project/Controller/?filter_array=["1","50","70"]

Although it's more cleaner, I read somewhere that you shouldn't use [] in url's but even if I use this way I will get two types of GET url's, the ajax URL ?filter_array%5B%5D=1&filter_array%5B%5D=50&filter_array%5B%5D=70. and the json url ?filter_array=["1","50","70"].

So I just need a solution that get's me just one type of GET url, so I can use the same url to ajax, and normal requests.


Solution

  • The standard way to pass an array of values is to pass the name with []'s repeatedly (url-encoded) as in your first example.

    You need to generate your URL in such a way that it complies with this...

    filter_array[]=1&filter_array[]=2&filter_array[]=3
    

    which, of course, encodes as you showed....

    filter_array%5B%5D=1&filter_array%5B%5D=2&filter_array%5B%5D=3
    

    If you stick with this format, your code will be more portable (eg ASP.Net will perform the conversion to List automatically as will many PHP libraries).

    Is there any reason you can't generate the url in this format?

    The difference here is that one is using standard forms encoding, the other is converting JSON