1

I need to get some parameters from URL using Javascript/jQuery and I found this nice function:

function getURLParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
};

So I started to use in my code but I'm having some issues since the parameter I'm looking for comes undefined. First, this is a Symfony2 project so Profiler gives me this information:

Request Attributes

Key                             Value
_route_params                   [registro => 1, solicitud => 58]
...
registro                        1
solicitud                       58

What I need from here is registro and solicitud. So what I did at Javascript side was this:

console.log(getURLParameter('registro')); // gets undefined

But surprise I get undefined and I think the cause is that registro is not present at URL which is http://project.dev/app_dev.php/proceso/1/58/modificar but it's present in the REQUEST. How I can get the registro and solicitud values from whithin Javascript? I need to send those parameters to a Ajax call, any advice?

Wouter J
  • 41,455
  • 15
  • 107
  • 112
ReynierPM
  • 17,594
  • 53
  • 193
  • 363

1 Answers1

1

Try using this function:

function getParameters(){
    var url = window.location.href; //get the current url
    var urlSegment = url.substr(url.indexOf('proceso/')); //copy the last part
    var params = urlSegment.split('/'); //get an array
    return {registro: params[1], solicitud: params[2]}; //return an object with registro and solicitud
}

Then you can call the function and use the values:

var params = getParameters();
console.log(params.registro);
console.log(params.solicitud);
Ragnar
  • 4,393
  • 1
  • 27
  • 40
  • 1
    The function looks good but is restricted to only this case and the idea is to make it _macro_ so that works for any parameter, not only for these two, have you any better ideas regarding this? – ReynierPM Feb 12 '15 at 16:05
  • If you want to write a function for general purpose you need to include each parameter's name in the URL for example: /registro/1/solicitud/48 in order to get key - value pairs – Ragnar Feb 12 '15 at 16:09
  • Another thing you can do is split the entire URL and if you know the position of each parameter in the array, you can get the value of each one. – Ragnar Feb 12 '15 at 16:13