3

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
Dr.Neo
  • 1,240
  • 4
  • 17
  • 28
  • 1
    `vars.push(hash[0]); vars[hash[0]] = hash[1];` - what for, why do you try to process `vars` both like an array and like an object? – raina77ow Oct 04 '12 at 12:19
  • Precisely @raina77ow - I just reviewed a piece of code that was trying to use this function, and I noticed the same thing. Bad code bites even after 4 years I suppose ;) – kamituel Feb 03 '16 at 11:55

6 Answers6

3

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.

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • As everything after the hash (#) is client side (from https://stackoverflow.com/a/12683131) the var "hashes" should be updated to ignore the task symbol #. Suggested: `var url_split_hashtags = window.location.href.slice(window.location.href.indexOf('?') + 1).split('#'); var hashes = url_split_hashtags[0].split('&');` – Wayne Liu Nov 12 '20 at 09:47
2

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.

wbq
  • 633
  • 4
  • 13
1

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);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

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, " "));
}
Lior
  • 5,841
  • 9
  • 32
  • 46
0

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/

WTK
  • 16,583
  • 6
  • 35
  • 45
0

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.

epascarello
  • 204,599
  • 20
  • 195
  • 236