Elegant way of retrieving query string parameter - javascript

I am retrieving one query string parameter, and for that my code is
Click me
Now I want to retrieve "status=pending" and for that I am doing
var qString = window.location.search.substring(1);
var Keys = qString .split('&');
alert(Keys[1]);
This works fine, but I am hard-coding [1] here. is there any elegent way of doing this without hard-coding?

I'd use a regular expression such as:
status=([a-zA-Z])+
This will retrieve only what the status is. If you already know the variable is always called status, but don't know what the value is, this is the right way to go.
To use it, you'd have to do something like this:
var qString = window.location.search.substring(1);
qString.match(/status=([a-zA-Z])+/);
Hope it helps

you can also consider a dedicated url/querystring parser, like this one

Try this out the easiest and best way without hard coding the index
params = location.search;
getParam = function(arg) {
if (params.indexOf(arg) >= 0) {
var pntr = params.indexOf(arg) + arg.length + 1;
if (params.indexOf("&", pntr) >= 0) {
return params.substring(pntr, params.indexOf("&", pntr));
} else {
return params.substring(pntr, params.length);
}
} else {
return null;
}
}
So you'd end up with something like:
?status=someValue
var val = getParam("status");
val would be "somevalue"

Related

window.location causing continuous loop using

I'm attempting to append to the URL, a query string based on a particular condition. The problem I'm having is, the following code causes the page to loop continuously:
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location;
window.location = myURL + "&debugMode=true&setIdleTime=60000";
}
}
taoExtendedIdleTime();
To correct this, I attempted the following, which checks if this query already exists. If not, add it:
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location;
if (myURL.indexOf("&debugMode=true&setIdleTime=60000") == -1) {
window.location = myURL + "&debugMode=true&setIdleTime=60000";
}
}
}
taoExtendedIdleTime();
In my dev environment, this doesn't get executed at all. When I add it to Console, I get the following error: Uncaught TypeError: myURL.indexOf is not a function, and references the fourth line of this snippet: if(myURL.indexOf...).
Any help/guidance you can provide is most appreciated!!
because you are trying to get an object. window.location will return you Location object. what you are looking for is window.location.href which will return url of current location.
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location.href;
window.location.href = myURL + "&debugMode=true&setIdleTime=60000";
} }
taoExtendedIdleTime();
Based on the documentation, window.location is a Location object (not a String), so it doesn't have an indexOf method. You might be interested in its search property though.
Or if you wanna go cleaner, URL.searchParams might help.

How to get values from a URL using hash and split

I have a url like this
http://localhost:9000/index.html#/acceptRequest?screen_name=kailash&rf=FIN1
Here I want to take FIN1 from the url and store it in another variable
I am using doing this in angularjs
I have made a function like this
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];
console.log(hash[1]);
}
return vars;
}
Here the console line hash[1] prints kailash FIN1.I only need the FIN1 to be stored and just print it in the console.How to make that happen?...
Anyway thanks in advance...
If the URL is for a resource in your Angular app, you can simply inject the $location service and use
var anotherVariable = $location.search().rf
See https://docs.angularjs.org/api/ng/service/$location#search
Here is simple solution for you.In core Javascript.
var url = "http://localhost:9000/index.html#/acceptRequestscreen_name=kailash&rf=FIN1";
var test = url.lastIndexOf('=');
var r = url.slice(test+1);
alert(r);
This code will get the url parameter you need. You just have to call it and tell what value you need.
function getUrlParameter(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
};
Use it like
var yourVariable= getUrlParameter("rf");
It will return the value of rf.
Hope this helps.
After some research i got an answer
we just have to store the return value of that function to a variable like this
var urlParams = getUrlVars();
then all we need to do is to
console.log(urlParams['rf']);
thats it...
anyway you guys have been a great help... Thank you for responding.

Passing parameter to json_callback function

I am using an inverse geolocation method from mapquest that looks something like this
function fieldVia_changed(a)
{
if (document.getElementsByName("via"+a)[0].value.trim().length!=0)
{
var via = document.getElementsByName("via"+a)[0].value ;
var strV = via.replace(/ |,/g, "+");
var s = document.createElement('script');
s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q='+strV+'&json_callback=cbv&format=json&polygon=1&addressdetails=1';
document.getElementsByTagName('head')[0].appendChild(s);
}
}
The results of the request are processed in the function cbv which accepts a parameter
function cbv(json)
{
v_lat[0] = json[0].lat;
v_lng[0] = json[0].lon;
}
However i need to be able to pass another parameter to the cbv function from fieldVia_changed function so that i can process the information properly. The cbv function definition would look like this function cbv(json,a). I looked all over but i can not find a solution. Is it possible ?
The server side won't usually have the option of passing additional arguments in a JSONP system. A possible solution is to use the value of a in the callback function name, and dynamically create the function as a kind of man in the middle between the cbv() function, allowing you to pass a as a second argument.
function fieldVia_changed(a) {
if (document.getElementsByName("via" + a)[0].value.trim().length != 0) {
// dynamically create the function
window['cbv_' + a] = function (json) {
cbv(json, a);
};
var via = document.getElementsByName("via" + a)[0].value;
var strV = via.replace(/ |,/g, "+");
var s = document.createElement('script');
// call the function cbv_x
s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q=' + strV + '&json_callback=cbv_' + a + '&format=json&polygon=1&addressdetails=1';
document.getElementsByTagName('head')[0].appendChild(s);
}
}
function cbv(json, a) {
v_lat[0] = json[0].lat;
v_lng[0] = json[0].lon;
console.log(a);
}
This is OK if a is some sort of short identifier, if it's from user input then it's not really suitable for use in the function name. You're using in the name attributes so I'm assume this is fine.

How to parse the first line of the http header?

Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,
First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.

passing multiple object to controller using ajax in ASP.NET MVC

I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});

Categories

Resources