Receive and send a javascript var - javascript

It is solved now
The problem was that I thought getParameterByName() was a defined function, but it is not the case so you need to add this function:
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 hope it helps newbies like me...
I need to receive a variable from the url and, if the user clicks on a button, then send it to another page. To do so, I have got the following code:
html
<input type="button" id="login-button" onclick="factura_si()" value="Yes"/>
Javascript
function factura_si() {
var n = getParameterByName('n');
var string_url = "https://www.webpage.php?" + "&n=" + n;
window.location = string_url;
}
When I use this script, the button does not redirect to the location. Is there something wrong with it?
The function
factura_si() {
var n = getParameterByName('n');
document.write(n);
}
returns nothing... But if I change the parameter 'n' by a random chain of letters 'grniegor', the button shows the chain.

Try setting window.location.href:
window.location.href = string_url;
window.location is an object describing the location of the current page. Setting it's href property causes the page to jump to the new url.

I probe this code and it works, if this does not work for you.
You can check the development tools, maybe the problem is elsewhere.
<input type="button" id="login-button" onclick="factura_si()" value="Yes"/>
the Js functions
function factura_si() {
var n = getParameterByName('n');
var string_url = "https://www.webpage.php?" + "&n=" + n;
window.location = string_url;
}
function getParameterByName(n) {
//call server or somthing...
return "somo_path";
}

Related

Two window.location not working togeather

I have two functions what sets a window.location.href tag in the url, but when I set the first one and then select the other one, the first one disappears. So how should I do? These functions are in a form that makes a selection of 1. project name and 2. package. And then you submit the form (php) the fields adds to the database.
function jsFunction(){
var myselect = document.getElementById("projektnamn");
window.location.href = "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
window.location.href = "?paket=" + select.options[select.selectedIndex].value;
}
I want the result to be like this:
domain.com?projektnamn=Something?paket=Something
What I get today is:
domain.com?projektnamn=Something
Or I get:
domain.com?paket=Something
I would store the link in a variable
let query = "";
function jsFunction(){
var myselect = document.getElementById("projektnamn");
query += "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
query += "?paket=" + select.options[select.selectedIndex].value;
window.location.assign(query);
}
Both of your functions are resetting the URL.
What you can do is use URLSearchParams to generate the query string.
function jsFunction(params) {
var myselect = document.getElementById("projektnamn");
params.set('projektnamn', myselect.options[myselect.selectedIndex].value);
}
function jsFunction2(params) {
var select = document.getElementById("paket");
params.set('paket', select.options[select.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params);
jsFunction2(params);
window.location.href = `${location.pathname}?${params}`;
From what it looks like you are trying to build a single function, not two separate functions. I would replace these 2 functions with one generic.
function jsFunction(params, id, name) {
var myselect = document.getElementById(id);
params.set(name, myselect.options[myselect.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params, "projektnamn", 'projektnamn');
jsFunction(params, "paket", 'paket');
window.location.href = `${location.pathname}?${params}`;

Pass Variables in Url in Framework7 Inside Pages

I am new to Framework7.io. I have got the following script which fetches the data from sqlite based on the parameters passed in the url.
However all the Js is called in index.html (the first page of F7), whereas I have get parameters in the inside pages.
code in b.html
<a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a>
code in a.html
function getParameterValue(type) {
type = type.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + type + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var type1 = getParameterValue('type');
Update:
Currently using this code with no successs.
$$(document).on('page:init', function (e) {
var page = e.detail.page;
myApp.alert(page);
if (page.name === 'a') {
var count = page.query.count;
myApp.alert(count);
// Now we can generate some dummy list
var listHTML = '<ul>';
for (var i = 0; i < count; i++) {
listHTML += '<li>' + i + '</li>';
}
listHTML += '</ul>';
// And insert generated list to page content
$$(page.container).find('.page-content').append(listHTML);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Thanks for your time and any help is highly appreciable.
Use page.query.your_url_parameter to get the parameter value.
Example:
To get <a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a> parameter :
$$(document).on('page:init', function (e) {
var page = e.detail.page;
if (page.name === 'a') {
var type = page.query.type; // returning "new"
var ok = page.query.ok; // returning "fine"
alert(type);
alert(ok);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Please see the documentation

object Object error javascript on response

I am working on a webpage where when I enter a word and press the button, it will show the meaning of the word. I am getting an [object Object] error instead of the meaning of the word.
Example:
Word I entered: code
Result through API:
{"Verb": ["attach a code to", "convert ordinary language into code"], "Noun": ["a set of rules or principles or laws (especially written ones", "a coding system used for transmitting messages requiring brevity or secrecy", "(computer science"]}
JS:
var links={
'meaning': 'link here',
}
var getMeaning = function(word){
totalLink = links.meaning + word;
var r = new XMLHttpRequest();
r.open("GET",totalLink, false);
r.send();
var data;
if (r.status===200){
var resp= JSON.parse(r.responseText);
data=resp;
}
else{
data='Error while running AJAX';
}
return data;
}
var PDictionary = function(){
this.meaning = getMeaning;
}
HTML:
<input id='a' type='text'><br>
<button id='b'>Do it</button>
<p class='out'></p>
<script type="text/javascript">
var dictionary = new PDictionary();
function done(){
get();
}
function get(){
var word=document.getElementById('a').value;
meaning = dictionary.meaning(word);
document.querySelector('.out').innerHTML = meaning;
}
var button = document.querySelector('#b');
button.addEventListener('click',function(){
get();
});
</script>
On my console RESPONSE tab, I am getting the meaning of the word but on the webpage, I get the error
You are not actually receiving an error when it returns [object Object]. That is just the string representation of your object. You will need to do something to pull the actual property names and values from the object itself. You could try a for loop like the example below.
var x, m = '';
for (x in meaning) {
m += x + "<br />" + meaning[x].join("<br />") + "<br /><br />";
}
Here is a JSFiddle to give you an idea of how you could implement it into your own code.
https://jsfiddle.net/up2jrzp6/

jQuery conditional on the url hash

In jQuery how can I check if a user is visiting a particular direct id link url?
For example:
http://mydomain.com/#foo
I this case, I like to check for foo.
Would love something like:
if(jQuery.urlHasHash("foo")) {
//logic here
}
No need for jQuery, your browser gives you all you need with document.location.hash
If you want to check if such an ID exists on your page:
var hash = document.location.hash.replace(/^#/, '');
if (document.location.hash != '' && document.getElementById(hash) {
// or just: $(document.location.hash)
// ...
}
Try this Demo http://jsfiddle.net/7QceB/
This might fit your needs :)
Code
$(function(){
//var href = location.href; // get the url
var href = "http://mydomain.com/#foo"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);
});
Try my jsFiddle : jsFiddle here
// it might be from browser & / anywhere else
var url = "http://mydomain.com/#foo";
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
console.log(page); // foo
or just
var url = "http://mydomain.com/#foo";
var page = url.substring(url.lastIndexOf('/') + 1); // #foo
After you can use if statement to know if (page == "foo")

How to check table for new content, and then update browser tab title?

I am working on a way to flash a browser tab when a new message appears in a table. I have the flashing of the tab part working, my only problem is that I can't seem to get it to flash when a message is received (which is the whole point of my exercise :) )
The newMessage() function is working fine, I just can't seem to get the notification() function to work.
My code is as follows:
function newMessage()
{
var oldTitle = "Your Page";
var msg = "New Message";
var timeout = setInterval(function()
{
document.title = document.title == msg ? '' : msg;
}, 1000);
window.onmousemove = function() {
clearInterval(timeout);
document.title = oldTitle;
window.onmousemove = null;
};
}
function notification()
{
var index = 2;
var content = document.getElementById('refreshMessages').childNodes[index];
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
var knownContent = content.toString();
updater.start();
updater2.start();
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}
notification();
In the notification() function, I am trying to call the newMessage() function by comparing the strings at the appropiate cell in the table.
I put the alert() into the else if just to see if it would be called, but it does not happen. update.start() and update2.start() are carried out however, as I can see the messages appearing in the table.
I would be happier to use JavaScript but I am open to jQuery also.
My JavaScript is very very rusty so excuse me if I have made any silly mistakes!
Thanks,
Chuck
You have several mistakes in function notification(), see my comments:
function notification()
{
var index = 2;
//Why are you assigning value to "content" for twice?
var content = document.getElementById('refreshMessages').childNodes[index];
/*
* function getElementByTagName is undefined, should be getElementsByTagName,
* 's' is missing. And [1] means the second one not the first one, make sure
* that's exactly what you want.
*/
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
/*
* content is a tr dom object, content.toString() is something like "[object]".
* If you want to get content inside a cell, you should use cell.innerHTML.
* e.g. A table:
* <table id="refreshMessages">
* <tr><td>Hello world</td></tr>
* </table>
* var table = document.getElementById('refreshMessages');
* var firstTr = table.getElementsByTagName("tr")[0];
* var firstTd = firstTr.getElementsByTagName("td")[0];
* alert(firstTd.innerHTML); //alerts "Hello world"
*/
var knownContent = content.toString();
//I doubt these functions really get invoked cuz there's javascript error above.
updater.start();
updater2.start();
//assigning twice, "getElementByTagName" is missing "s"
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
//Remove toString(), use innerHTML i metioned above.
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
//You miss an "=" here, to judge a equals b, you should use "=="
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}

Categories