Dr.Neo
Dr.Neo

Reputation: 1280

function to retrieve url variables using javascript and Jquery?

in my script there a simple list shows links for editing

<ul>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
</ul>

what i need is to read the variable id so i can send it through .ajax call and i tried this function

$(document).ready(function(){
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1)
                                         .split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
     }
     $('.edit').click(function(){
         var test = getUrlVars()["id"];
         alert(test);
     });
});

When I clicked on the link, the alert message shows undefined.

I tried another function:

$(document).ready(function(){
    var urlParams = {};
    (function () {
        var match,
               pl = /\+/g,  // Regex for replacing addition symbol with a space
           search = /([^&=]+)=?([^&]*)/g,
           decode = function(s) { 
               return decodeURIComponent(s.replace(pl, " ")); 
           },
           query  = window.location.search.substring(1);
           while (match = search.exec(query))
               urlParams[decode(match[1])] = decode(match[2]);
     })();
     $('.edit').click(function(){
         var test = urlParams["id"];
         alert(test);
     });
 });

... but even this also shows up the alert message undefined.

Upvotes: 3

Views: 5092

Answers (6)

wbq
wbq

Reputation: 662

You could try this:

JavScript

function getUrlParams() {
    var params = {};
    location.search.replace(/\?/g, '').split('&').forEach(function(item) {
      params[item.split('=')[0]] = item.split('=')[1];
    });
    return params;
}

The function will return an object like this:

{
  firstName: 'Jordan',
  lastName: 'Belfort',
  position: 'The Wolf of Wall Street',
}

Usage

var urlParams = getUrlParams();
alert('Hello ' + urlParams.firstName + ' ' + urlParams.lastName);

Note: There's actually no need to use location.href and split the url at '?', since we can get the whole query string with location.search.

Upvotes: 2

epascarello
epascarello

Reputation: 207501

Change it to use an object, not an array.

function getUrlVars() {
    var vars = {}, //<--object
    hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1)
                                     .split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];  //<--add to the object
    }
    return vars;  //<--return the object
 }

Also you can use window.location.search so you do not have to do that initial slice.

Upvotes: 0

WTK
WTK

Reputation: 16971

You almost got it right the first time, you just have to declare vars as object and get rid of vars.push(...).

Here's working example - http://jsfiddle.net/KN9aK/1/show/?id=yoursuperduperid

Source here http://jsfiddle.net/KN9aK/1/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

As an alternative to your problem, why not put the id part of the href into a data parameter and read that? It would save you having to dissect the URL. Try this:

<ul>
    <li><a href="edit.php?id=5" data-id="5" class="edit">click here</a></li>
    <li><a href="edit.php?id=6" data-id="6" class="edit">click here</a></li>
    <li><a href="edit.php?id=7" data-id="7" class="edit">click here</a></li>
    <li><a href="edit.php?id=8" data-id="8" class="edit">click here</a></li>
</ul>
$('.edit').click(function(){
    var id = $(this).data("id");
    alert(id);
});

Upvotes: 1

sp00m
sp00m

Reputation: 48817

The methods your tried don't take an URL as argument, but parse the current URL parameters (i.e. the URL within your brother). Just modify the first method like this to make it work:

$(function() {
    function getUrlVars(url) {
        var vars = [], hash;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    $('.edit').click(function() {
        var href = $(this).attr("href");
        var test = getUrlVars(href)["id"];
        alert(test);
    });
});

Side note: you could also modify the second one, both of them do the same job.

Upvotes: 3

Lior
Lior

Reputation: 6051

Try this one:

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

Upvotes: 0

Related Questions