Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to get parameters of a url?

New to jQuery and I'm having trouble getting the parameters of a url that my server generates. I have a url like this:

<span class="popuptest"><a href="www.example.com/test?param1=1&param2=2">find param</a></span>

my jquery function looks like so:

$(function() {
  $('.popuptest a').live('click', function(event) {
  $.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = this.href.slice(this.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;
    },
    getUrlVar: function(name){
      return $.getUrlVars()[name];
    }
  });
  var second = getUrlVars()["param2"];
  alert(second);
  return false;
  });
});

clicking on the link should show me "2", however I get nothing... any help for a jQuery noob? thanks in advance!

I found this on a blog: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

like image 340
thedeepfield Avatar asked Feb 22 '11 04:02

thedeepfield


People also ask

How do I find the parameter of a URL?

Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.

What is jQuery param?

jQuery param() Method The param() method creates a serialized representation of an array or an object. The serialized values can be used in the URL query string when making an AJAX request.

What is URLSearchParams?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


1 Answers

You don't need jQuery for that purpose you can use the pure JavaScript:

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

and you can call the function in this way..getParameterByName(param1,href of your link)

DEMO

like image 155
Vivek Avatar answered Nov 08 '22 20:11

Vivek