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?

3
  • split the url segments after .php Commented Feb 12, 2015 at 15:38
  • @charlietfl example? Commented Feb 12, 2015 at 15:40
  • could also pass a variable from php to javascript that contains the url params when page loads Commented Feb 12, 2015 at 15:41

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.