Tayyab Vohra
Tayyab Vohra

Reputation: 1662

How to get the value from query string in jQuery

I am passing the value of username into the query string but i am unable to get the value of the name in jquery.

this is my url

https://dev.hudpowerbid.com/front-end-pm/?fepaction=newmessageShami%20Kothari

I want to get only Shami Kothari

this is how i am attaching the name with the query string

var name= jQuery(this).parent().siblings(".htb200").html();
window.location.href ='https://example.com/front-end-pm/?fepaction=newmessage'+name;

this is how i am attaching name with url now i want to get this in jquery

this is how I am getting the value.

function getUrlVars() {
var url = 'https://example.com/front-end-pm/?fepaction=newmessage'+name;
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');

for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}

Upvotes: 0

Views: 26

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50639

Your issue is that you are not assigning a key "name" to the value "Shami Kothari" in your query string, instead you are currently just appending it to the end of another value. To add the key "name" to your query string you can use & to specify another key-value pair:

window.location.href ='https://example.com/front-end-pm/?fepaction=newmessage&name='+name;

This way when you try and get name, it will look for the key "name" and retrieve the value, which is "Shami Kothari"

See working example below:

function getUrlVars() {
  var name = "Shami Kothari";
  var url = 'https://example.com/front-end-pm/?fepaction=newmessage&name=' + name;
  var vars = {};
  var hashes = url.split("?")[1];
  var hash = hashes.split('&');

  for (var i = 0; i < hash.length; i++) {
    params = hash[i].split("=");
    vars[params[0]] = params[1];
  }
  return vars;
}

console.log(getUrlVars());

Upvotes: 1

Related Questions