response.sendRedirect("http://localhost:8080/cse/welcome.html?first=fname&last=lname&dname=dept&mname=mobno");
How to extract the first,last,dname,mname parameters from the Url and I want to use those extracted values in my redirected html document(welcmoe.html). How can I achieve this?
If you wanted client side using JS, you could do the following.
//Create an array from query strings
//such as ['first=fname', 'last=lname', ...]
var querystring = location.search.substring(1).split("&");
var props = {};
//Loop thru the array
querystring.forEach(function(item) {
//split each item
var item = item.split("=");
//set the first part as key and last/second part as value
props[item.shift()] = item.pop();
});
alert ("first: " + props["first"]);
alert ("last: " + props["last"]);
//and so on...
The four variables from the java servlet can be hardcoded and passed as a string like this
StringBuilder url =new StringBuilder();
url.append("http://localhost:8080/cse/welcome.html");
url.append("?first="+fname);
url.append("&last="+lname);
url.append("&dname="+dept);
url.append("&mname="+mobno);
String URL=url.toString();
String urlEncoded=response.encodeRedirectURL(URL);
response.sendRedirect(urlEncoded);
Then these variables can be obtained and called in the javascript in this way
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var fname = getParameterByName('first');
var lname=getParameterByName('last');
var dept=getParameterByName('dname');
var mobno=getParameterByName('mname');
</script>
Related
I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value:
www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
As to your regex question, testing if the pattern #page=(number) or &page=(number) is present combined with capturing the number, can be done with the regex /[#&]page\=(\d*)/ and the .match(regex) method. Note that = needs escaping in regexes.
If the pattern exists in the string, result will contain an array with the integer (as a string) at result[1]. If the pattern does not exist, result will be null.
//match #page=(integer) or &page=(integer)
var test = "#foo=bar&page=1";
var regex = /[#&]page\=(\d*)/;
var result = test.match(regex);
console.log(result);
If you want to dynamically set the key= to something other than "page", you could build the regex dynamically, like the following (note that backslashes needs escaping in strings, making the code a bit more convoluted):
//dynamically created regex
var test = "#foo=bar&page=1";
var key = "page"
var regex = new RegExp("[#&]" + key + "\\=(\\d*)");
var result = test.match(regex);
console.log(result);
I'm trying to use javascript to complete something that i've done a ton of times in PHP.
I have two instances of urls that come into my site. One from a tracking link... and another from search or share, so on...
tracking link: www.foo.com/blog?offer=pine&sub_id=123
non paid search link: www.foo.com/blog
I'd like to detect if my link has a string, and if so pass the offer into a url within the page. In PHP i'd do this like so.
<?php
if(array_key_exists('sub_id', $array)) {
$my_variable = $array['sub_id'];
} else {
$my_variable = 'my default value';
}
?>
<a class="submitbutton" href="www.joinmywebsite.com/join?offer=pine&sub_id=<?php echo $my_variable; ?>">Join My Site</a>
Is it possible to do this with javascript? I've search and search and ever function I find either returns the value of the string parameter or it sees nothing and does nothing.
Thanks.
Sure:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(
results[1].replace(/\+/g, " "));
}
var subId = getParameterByName('sub_id') || 'my default value';
$(function(){
$('a.submitbutton')
.prop({ href: 'www.joinmywebsite.com/join?offer=pine&sub_id=' + subId });
});
Source: How can I get query string values in JavaScript?
If I understand your question, this should be the answer:
<script type='text/javascript'>
function getUrlVars()
{
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
return vars;
}
var path = window.location.href;
var position = path.indexOf("sub_id");
if (position != -1)
var desired = getUrlVars()["sub_id"];
else
var desired = 'my default value';
//alert(desired);
</script>
<a class="submitbutton" onClick="document.location.href='http://www.joinmywebsite.com/join?offer=pine&sub_id=' + desired;">Join My Site</a>
I have a problem , my original URL looks like this:
test.com/?manufacturer=0&body-style=0&min-price=270%2C000&max-price=780%2C000
As you can see, the min-price and max-price values in the query string is not correct due to the comma that is passed to the URL. It should be in their respective integer value like min-price=270000 and max-price=780000.
I need to convert the query string values of min-max and max-price using jQuery. I currently do not how to do this actually. But I have codes to get them from the URL and then convert them to the correct value. I just don't know how to implement them back to the URL (as new URL) using jQuery. These are my existing codes:
//Function to get value of parameter in query string
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
//Function to remove commas and convert to number
function convert_to_pure_number(x) {
//Remove commas
var x_withoutcommas=x.replace(/,/g,'');
//Convert to plain number
var y =parseInt( x_withoutcommas ,10);
return y;
}
var min_price_original=getParameterByName('min-price');
var max_price_original=getParameterByName('max-price');
var min_price_converted=convert_to_pure_number(min_price_original);
var max_price_converted=convert_to_pure_number(max_price_original);
Any suggestions how will I continue the above code with the additional code to put them back to the URL posted? Thanks for any help.
UPDATE
This is the process:
Form will be posted to the server--> URL will contain commas --> My new code will remove the comma --> In the query string value, correct value will be used.
Cheers.
use replace function like this :
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var min_price_original=getParameterByName('min-price').replace('%2C','');
var max_price_original=getParameterByName('max-price').replace('%2C','');
I have got a current URL looking like this:
http://example?variables1=xxxx&example&variables2=yyyyy
I want to use the variables1 and variables2 to create a new URL and open this new URL:
http://example?variables3=variables1&example&variables4=variables2
I hope someone can help me with this :)
You will need to parse the desired query parameters from the first URL and use string addition to create the second URL.
You can fetch a specific query parameter from the URL using this code. If you were using that, you could get variables1 and variables2 like this:
var variables1 = getParameterByName("variables1");
var variables2 = getParameterByName("variables2");
You could then use those to construct your new URL.
newURL = "http://example.com/?variables1=" +
encodeURIComponent(variables1) +
"&someOtherStuff=foo&variables2=" +
encodeURIComponent(variables2);
Because I don't fully understand what needs to change, here's my best attempt*, using a mashup of other answers and resources online.
// the original url
// will most likely be window.location.href
var original = "http://example?variables1=xxxx&example&variables2=yyyyy";
// the function to pull vals from the URL
var getParameterByName = function(name, uri) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(uri);
if(results == null) return "";
else return decodeURIComponent(results[1].replace(/\+/g, " "));
};
// so, to get the vals from the URL
var variables1 = getParameterByName('variables1', original); // xxxxx
var variables2 = getParameterByName('variables2', original); // yyyyy
// then to construct the new URL
var newURL = "http://" + window.location.host;
newURL += "?" + "variables3=" + variables1;
newURL += "&example&"; // I don't know what this is ...
newURL += "variables4=" + variables2;
// the value should be something along the lines of
// http://example?variables3=xxxx&example&variables4=yyyy
*All of which is untested.
Suppose that I have a URL like the following:
http://localhost:8000/intranet/users/view?user_id=8823
Now, all I want to do is to get the value of the URL using JavaScript and parse it, taking the user_id value (which is 8823 in this case) and sending that value through an iframe.
How can I do this?
try this code
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, " "));
}
i found it at How can I get query string values in JavaScript?
Try using window.location.href or document.URL
Do this:
var matches = document.location.search.match( /user_id=(\d+)/ );
if ( matches != null )
{
alert( matches[ 1 ] );
}
matches[ 1 ] will contain the user ID.
document.location.search contains the query string (all of the parameters which follow the '?' including the '?').
var test = "http://localhost:8000/intranet/users/view?user_id=8823";
//var url = document.URL;
var url = test.split("=");
var urlID = url[url.length-1];
document.write(urlID);
window.frames["myIframe"].yourMethod(urlID);