Using the parameter passed by URL in JavaScript - javascript

I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
var x;
//geting the username
x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = x.substring(x.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
//to get the username parameter from URL on new page
var z=window.location.search.substr(1);
//to get rid of some part of the username parameter
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
//to put the username to 'To' field
document.getElementById("search-q").value= a;
}
Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!

What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.

ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
var y;
//geting the username
y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>
<script>
//code running after page-load
window.onload = function() {
var z=window.location.search.substr(1);
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
document.getElementById("search-q").value= a;
}
</script>

Related

Javascript redirect using windows.locaton.href OR windows.locaton.replace is not working. Error: window not defined

I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.

how to use local storage in a proper way

i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);

Intercept incoming URL with javascript

When a user navigates to my site with a qualified URL (e.g. mysite.com/abc.html) I want to call a javascript function first before showing any pages. I need that because my site is driven by ajax.
I have a function that’s called when the page is first loaded:
<body onload="FirstJSFunction(150);”>
That function will intercept the URL and do what I want, but only if the qualified URL is mysite.com/index.html. Any other valid URL within the site will bypass the javascript function and load the requested page. That’s not what I want.
Here is how FirstJSFunction handles it:
<script>
function FirstJSFunction(type) {
var gurl = GetURL();
length = gurl.length;
console.log("SFR URL " + length);
var pos = gurl.lastIndexOf("/");
console.log ("SFR_LastFwdSlash " + pos);
if (length > pos) {
var sub1 = gurl.substr(pos, length);
console.log ("SFR_Sub1 " + sub1);
sub2 = sub1.substr(1, 5);
console.log ("SFR_Sub2 " + sub2);
if (sub2 == "index") {
ShowAjax(3);
return true; }
if (sub2 != "index") {
ShowAjax(3);
return true; }
}
</script>
<script>
function GetURL() {
var loc_href = location.href;
console.log ("URL " + loc_href);
var length = loc_href.length;
console.log ("Length " + length);
var pos = loc_href.lastIndexOf("/");
console.log ("LastFwdSlash " + pos);
var pos2 = loc_href.indexOf("/");
console.log ("FwdSlash " + pos2);
if (length > pos) {
var substr = loc_href.substr(pos, length);
console.log ("Substring " + substr);
return substr; }
}
</script>
So my question is: when the user navigates to my site with any URL other than mysite.com or mysite.com/index.html – for example mysite.com/abc.html – why doesn’t the code above work to intercept the URL and call the javascript function, as happens if the URL is index.html.
Just to clarify, I only want to intercept the first incoming URL. I am not looking to intercept any URL the user enters into the address bar after they have arrived at my site.
Thanks for any help on this.
I'm not sure about everything you explained, so making some assumptions here.
But if that JS code is only on index.html, then it will never run for any other page. For that you would need to include it in every page.
Only the server is able to "see" all the pages accessed by your users.

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

Display summary of choices in JS

this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')

Categories