0
votes

CakePHP URL query parameters are not done in a standard fashion e.g. the params are /param1:value1/param2:value2 instead of ?param1=value1&param2=value2

This means that the javascript location.search does not return a value.

There is a getQueryParams JQuery plugin that does what I want using location.search

I have had to modify this to use

var pairs = location.pathname.split('/');

instead of

var pairs = location.search.substring(1).split('&');

However this now includes everything except the host in the variable pairs. So I have to check for a ':' to see if it is a parameter.

This works - but is there a better (more Cake like) way of doing it? I don't want to improve on the JQuery plugin (e.g. Regex), I want to find a better way to integrate the plugin with CakePHP.

Upddate: I've removed the rest of the JQuery code as I'm happy with the jquery code, my issue is with fitting it more with cake

Is there some 'Cake like' way of removing the path to your app, the model and the controller from location.pathname so that you end up what you would normally get from location.search?

2

2 Answers

1
votes

Since you're searching for a particular parameter, you can use a regular expression:

$.getQueryParam = function (param) {
    var re = new RegExp(param+':([^\/]+)');
    var matches = location.pathname.match(re);
    if (matches.length) {
        return matches[1];
    }
    return undefined;
}
0
votes

So it appears there isn't a better way of doing it. Here is the javascript for reference:

// jQuery getQueryParam Plugin 1.0.1 (20100429)
// By John Terenzio | http://plugins.jquery.com/project/getqueryparam | MIT License
// Modified by ICC to work with cakephp
(function ($) {
    // jQuery method, this will work like PHP's $_GET[]
    $.getQueryParam = function (param) {
        // get the pairs of params fist
        // we can't use the javascript 'location.search' because the cakephp URL doesn't use standard URL params
        // e.g. the params are /param1:value1/param2:value2 instead of ?param1=value1&param2=value2
        var pairs = location.pathname.split('/');
        // now iterate each pair
        for (var i = 0; i < pairs.length; i++) {
            // cakephp query params all contain ':'
            if (pairs[i].indexOf(':') > 0) {
                var params = pairs[i].split(':');
                if (params[0] == param) {
                    // if the param doesn't have a value, like ?photos&videos, then return an empty srting
                    return params[1] || '';
                }
            }
        }
        //otherwise return undefined to signify that the param does not exist
        return undefined;
    };
})(jQuery);