Parameter not work properly - javascript

This script not work properly. I want to print value in parameter of url file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
var tech = GetURLParameter('t');
var blog = GetURLParameter('b');
document.getElementById("demo").innerHTML ="value is " + blog+ " "+ tech;
<html>
<body>
<a id="demo"></a>
</body></html>

This will get your parameters from the string:
'file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind'
function GetURLParameter(sParam, str)
{
sParam = sParam.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + sParam + "(=([^&#]*)|&|#|$)"),
results = regex.exec(str);
if(!results)
{
console.log('no param')
}else
{
console.log((results[2].replace(/\+/g, " ")))
}
}
var tech = GetURLParameter('t', 'file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind');
var blog = GetURLParameter('b', 'file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind');

Related

Get html data attributes from URL

I want to send prodName and prodItem into a URL that will be captured by product.html so when a user clicks on a product (index.html), a URL will be created and that URL will be used but on product.html. I want to catch prodName and proItem and put the text in the product.html but the value will be null.
index.html
$(".product-item").each(function(index, value) {
var prodName = $(this).children("h2").attr("data-prodname");
var prodItem = $(this).children("h2").attr("data-proditem");
var link = $("<a href='product.html?prodName=" + prodName + "&prodItem=" + prodItem + "'/>");
console.log(prodName);
console.log(prodItem);
$(this).children("img").wrap(link);
});
})
product.html
$.urlParam = function (parameterName) {
var results = new RegExp('[\?&]' + parameterName + '=([^&#]*)').exec(window.location.href);
if (results === null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
var adminSerial = $.urlParam('ProdName');
var dashboardName = $.urlParam('ProdItem');
$('#product').html("The text is " + adminSerial);
I put this code on pruduct.html and now it works.
var getParams = function (url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
return params;
};
var mylocation ={};
var mylocation = getParams(window.location.href);
console.log(mylocation.prodName);
$('#product').html(mylocation.prodName);
$('#item').html(mylocation.prodItem);

how to get parameters from url in javascript?

I am trying to get query parameters from the URL in javascript. I tried window.location.search and got the params but it happens only the first time I access the URL. Afterwards it is returning empty.
I read somewhere that it is due to Asynchronous GET request. So how to get parameters always from the URL in javascript?
This might can help for you.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
function Myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id="); //will return the parameter after "?"
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
You can use the new javascript APIs, URL and URLSearchParams
var link = new URL('https://google.com.ec?q=blable%20bli&q=2312&dog=true')
var params = link.searchParams
var keys = [...new Set([...params.keys()])]
console.log('keys: ', keys)
for (var key of keys)
console.log(key, params.getAll(key))

How to initialize an element in an HTML page

I want to pass through the text data entered on the /index page (property address) and (email) to the /sign-up page.
problem:
The query string(s) are moving into the URL, however how do I populate the respective fields on the /sign-up page, with the text data provided in the URL?
www.juwai.kiwi
<script>
(function(f, e, t){
initForm(f, e, t);
}(document.forms[0],'full_name',document.getElementsByName('full_name').valueOf()));
</script>
<script>
function initForm(oForm, element_name, init_txt) {
frmElement = oForm.elements[element_name];
frmElement.value = init_txt;
};
var queryStrng = [
{
full_name: "dave",
email: "email#to.do",
property_address: "prop address to do"
}
];
//queryStrng[0].full_name = document.getElementsByName("full_name").valueOf();
//var oFormObject = document.forms[0];
</script>
Try this function:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
http://www.juwai.kiwi/sign-up.html?property_address=abcd&email=myemail%40gmail.com
var property_address = GetURLParameter('property_address');
var email = GetURLParameter('email');`

How get params from url to javascript or jquery file?

For example js file include to page:
<script src="/js/example/test.js?count=2321"></script>
How get value count in javascript file test.js from url /js/example/test.js?count=2321?
P.S.: how get if i do not know position key? i.e. how get value parametr from key?
Define a method like below to fetch all key values from a url:
function getUrlVars(url)
{
var vars = [], hash;
if(url == undefined || url.indexOf('?') == -1)
return vars;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push({key : hash[0] , value : hash[1]});
}
return vars;
}
this method returns an object array that contains all available Key/Values of the url.
finally you can get the src from any script tag and get all available Key/Values like this:
$("script").each(function(){
if($(this).attr("src") != undefined){
console.log($(this).attr("src") + ":");
console.log(getUrlVars($(this).attr("src")));
}
});
$(document).ready(function(){
function getUrlVars(url)
{
var vars = [], hash;
if(url == undefined || url.indexOf('?') == -1)
return vars;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push({key : hash[0] , value : hash[1]});
}
return vars;
}
$("script").each(function(){
if($(this).attr("src") != undefined){
console.log($(this).attr("src") + ":");
console.log(getUrlVars($(this).attr("src")));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?count=2321&customKey=1233&customKey2=sdffds"></script>
<script src="/js/example/test1.js?count2=2321&Key2=sdffds"></script>
<script src="/js/example/test2.js?count2=2321&key1=1233"></script>
You can also use the following method to get a specific key from any url:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
and get the value of a key like this:
getParameterByName("count", $("script[src*='test.js']").attr("src"))
$(document).ready(function(){
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
console.log( getParameterByName("count", $("script[src*='test.js']").attr("src")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?count=2321"></script>
Edit (Detect current script): There are many ways to detect the current script tag that you can find HERE, but I think the most accurate way is to define a method in each of your scripts with its name on it and loop over all scripts to find the script you want:
function isMe(scriptElem){
return scriptElem.getAttribute('src') === "Your Current Script Src";
}
var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if( isMe(scripts[i])){
me = scripts[i];
}
}
console.log( getParameterByName("count", $(me).attr("src")));
Try something like this.
Loop on <script>, search the script that you want and cut at the parameter ?
$(document).ready(function(){
var parameters = $("script[src*='test.js']").attr("src").split('?')[1].split('&');
var count="Not found";
for(var i=0;i<parameters.length;i++)
{
var param=parameters[i].split('=');
if(param[0]=="count")
count=param[1];
}
console.log(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?not=2321&over=blabla&one=two&count=1234"></script>
Try This
function getParameterByName(name,url)
{
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function(){
var url = $("script[src*='test.js']").attr("src");
getParameterByName('count',url);
});
You can also do it like this:
Give an id to your script:
<script id="YourId" src="/js/example/test.js?count=2321"></script>
And then:
$(document).ready(function() {
alert($("#YourId").attr('src').split('=')[1]);
});
var paramCount = getParameterByName('count');
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(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(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

Categories

Resources