How to refresh a separate page to get PHP session variables? - javascript

Before I start, I need you to know that my methods aren't the best. I'm a beginner to JavaScript and php and I'm sure that what I'm trying to accomplish can be accomplished by much better and simpler means.
I think my problem lies with session variables and printing pages. I have a page where a user creates tables from dropdown lists. I need to print the tables but on three different pages and in three different formats. I have the three pages linked to print using an the "frames["iframe].print" function.
Here are my frames:
<iframe src="customer_detail.php" style="display:none;"name="framed"></iframe>
<iframe src="advisor_copy.php" style="display:none;" name="framez"></iframe>
<iframe src="customer_copy.php" style="display:none;" name="frame"></iframe>
And my buttons:
<span id = "cCopy"><button class = "button" onclick= "frames['frame'].print();"/> Customer Copy</button></span>
<span id = "aCopy"><button class = "button" onclick="frames['framez'].print();" value="Advisor_Copy">Advisor Copy</button> </span>
<span id = "cCopy"><button class ="button" onclick= "frames['framed'].print();" value="customer_copy">Customer Detail </button></span>
From what I understand, the page needs to be refreshed in order for the session variables to update. My hack solution which works is to refresh the 3 pages I'm printing(customer_detail, customer_copy and advisor_copy) every 1 second. What I'd much rather have is the ability to refresh the page I'm printing when I click one of the three buttons so I can update the session variables being called on those pages.
I've tried refreshing the iframe with an onclick event but it doesn't do exactly what I need it to. I've searched around for various solutions and none of them have really worked. If I need to restructure my code then I will. I think what I really should do is pass the variables I need to the other pages via an AJAX call. I'd like to know if there's a solution which will allow my code to function without having to more or less start from scratch.

Ok. This is a ugly workaround without rewrite all.
<span id = "cCopy"><button class = "button">Customer Copy</button> </span>
<span id = "aCopy"><button class = "button" value="Advisor_Copy">Advisor Copy</button> </span>
<span id = "cCopy"><button class ="button" value="customer_copy">Customer Detail </button></span>
<br>
<iframe name="framed"></iframe>
<iframe name="framez"></iframe>
<iframe name="frame"></iframe>
WORKING EXAMPLE
UPDATE
...and on single PHP pages, on body tag put... <body onload="window.print()">
UPDATE 2
and if you want to remove underline button text add
style="text-decoration:none;"
on each <a tag
UPDATE 3 (it is necessary to carry some tests, due to the browsers security locks)
Your index.html:
<span id = "cCopy"><button onclick="printIframe('framed')" class = "button">Customer Copy</button></span>
<span id = "aCopy"><button onclick="printIframe('framez')" class = "button" value="Advisor_Copy">
Advisor Copy</button></span>
<span id = "cCopy"><button onclick="printIframe('frame')" class ="button" value="customer_copy">Customer Detail</button></span>
<br>
<div id='frames'>
</div>
<script>
var iframes = {}; //create a 'container' for iframe
iframes['framed'] = 'customer_detail.php'; // your link
iframes['framez'] = 'advisor_copy.php'; // your link
iframes['frame'] = 'customer_copy.php'; // your link
// if you want to add another iframe create a new line with iframes['myIframeName'] = 'MyIframeUrlLink'; // your link
for (var k in iframes){
createIframe(k, iframes[k]);
}
function printIframe(id) //this call a javascript print function inside your PHP - need for security reason
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
//this create iframes
function createIframe(name, src) {
var i = document.createElement("iframe");
i.name = name;
i.id = name;
i.src = src;
i.style= "display: none";
document.getElementById("frames").appendChild(i);
};
</script>
In your PHP Pages, remove my onload="window.print()" and at the end of body tag, just before </body> to be clear, add:
<script>
function printPage() { print(); }
</script>
like this:
</body>
<script>
function printPage() { print(); }
</script>

function refreshPage() {
$("#widgetbox").fadeOut(750, function() {
<!-- empty the current content and then fetch new data -->
$("#widgetbox").empty
<!-- load the getPage.php file which will replace all the
$("#widgetbox").load("getPage.php", function() {
$("#widgetbox").fadeIn();
});
});
};
<!-- initiate the function above -->
$(function(){
refreshPage();
<!-- set the interval for refreshing, default set to 1.0 seconds -->
var int = setInterval("refreshPage()", 1000);
});
study this
http://websitetutorials.net/jquery/rotate-product-listings-php-and-jquery
and modify it

Related

How to change parameter inside the function on different buttons click

I have 3 buttons
<div id='dwbuttons' class="cards">
<div>
<div class="image-div">some image here</div>
<a id="Autotune" class='Autotune' href="whait.html" target="_blank">autotune</a>
</div>
<div>
<div class="image-div">some image here</div>
<a id="Complete" class='Complete' href="whait.html" target="_blank">Cmplete</a>
</div>
<div>
<div class="image-div">some image here</div>
<a id="FLstudio" class='FLstudio' href="whait.html" target="_blank">FLstudio</a>
</div>
</div>
each button should downloads different type of file and all this handles one fuction (downloadURI)
let Auto = document.getElementById('Autotune')
let complete = document.getElementById('Complete')
let flstudio = document.getElementById('FLstudio')
let buttons = document.getElementById("dwbuttons")
function downloadURI(uri, name) {
name = ''
uri = ''
let link = document.createElement("a");
link.setAttribute('download', name);
link.href = uri;
document.body.appendChild(link);
link.click();
link.remove();
}
buttons.onclick = function(){
setTimeout(
downloadURI, 1000
)
}
How can I change the parameters of "name" and 'uri' to 'name = flstudio' and "uri = flstudio" when related button is clicked?
What i need:
When button 1 is clicked - name = Autotune, uri = autotune
When button 2 is clicked - name = Complete, uri = complete
...
Im really stuck here
I can make 3 different functions with name and uri i needed and then another 3 to call them onclick, but it will be a mess, if assume I will have 15 buttons. Maybe array is a way to go here, but i dont have enough knowledge yet.
What I would recommed would be the following.
Give all your buttons the same class, and give each button data- attribute, cotaining the information you need. Then, with simply JQuery, you can retrieve those, for example, on-click.
<a class='button Autotune' href="whait.html" data-name="autotune" data-uri="example.com" target="_blank">autotune</a>
<a class='button Autotune' href="whait.html" data-name="autotune2" data-uri="example2.com" target="_blank">autotune</a>
<a class='button Autotune' href="whait.html" data-name="autotune3" data-uri="example3.com" target="_blank">autotune</a>
The JQuery would be something like following
$(document).ready(function(){
$('.button').on('click', function(){
$(this).attr('data-name');
$(this).attr('data-uri');
});
});
This way you can have only one function, that can do all the hard work for you.
Note that this function only retrieves data from each button, you will need to extend this function as you need to.

Iterate through buttons by class and display data from parent div of the selected button in a modal

I have been trying for days now to figure out what I am doing wrong here. I have buttons for items that are located on different pages and they all use the same modal that contains a form and item details, depending on which button is selected.
The buttons have the same class and when clicked I need to get the attributes from the button's parent div (several divs above the button) and display the data from parent div in the modal. I am using Wordpress and I cannot add the attributes to the buttons, so I had to add them to a parent div.
I can get the code to work perfectly in visual studio but when I add it to Wordpress I keep getting errors in the console stating "Can't create duplicate variable that shadows a global property: 'l'" and "Can't create duplicate variable: 'modalBtns'". I cannot use button onclick for the buttons as Wordpress restricts that from what I have read, so I have to do it another way.
I have scoured Google and tried every suggestion I have found on this site and many others. I renamed 'modalBtns', broke code down into functions and put the functions outside the loop, added the functions inside the loop, changed modalBtns to var, constant..nothing is working. I don't know how to clear the errors.
I am also having issue with the modal not getting the data as the code has already ran prior to the modal loading so the id's for the modal divs I am putting the data in are not even present when code runs. I have to add item name to a hidden field of the form and add image, price, description. I tried delaying the code in the section where it is looking for modal divs but it still doesn't work.
This is what I have that works in Visual Studio but not on Wordpress. I don't know what I am doing wrong.
<div class="modalBtn" data-pkg="Package #1" data-price="124" data-duration="month" data-desc="This + that" data-img="main">
<div id="otherDiv">
<button id="Package1" class="premium-price-pricing-button">Package 1</button>
</div>
</div>
<div class="modalBtn" data-pkg="Package #2" data-price="234" data-duration="month" data-desc="Another descrpition" data-img="thumbnail">
<div id="otherDiv">
<button id="Package2" class="premium-price-pricing-button">Package 2</button>
</div>
</div>
<div class="modalBtn" data-pkg="Package #3" data-price="345" data-duration="each" data-desc="" data-img="custom">
<div id="otherDiv"></div>
<button id="Package3" class="premium-price-pricing-button" >Package 3</button>
</div>
<div id="modal">
<h1 id="modalTitle">This is the title</h1>
<img id="modalImg" src="defaultImg.png"/>
<p><span id="modalPrice">100</span><span id="modalDuration">month</span><span id="modalDesc">Description here</span></p>
<form action="/action_page.php">
<label for="name">First name:</label><br>
<input type="text" id="name" name="name" value="John"><br>
<label for="pkg">Package:</label><br>
<input type="text" id="pkg" class="pkgFormField" name="pkg" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</div>
This is the code
//Get all buttons with classname premium-price-pricing-button
let modalBtns = document.getElementsByClassName('premium-price-pricing-button');
//Iterate through buttons & add event listener, when clicked run updateModal function
for (var i = 0; i < modalBtns.length; i++) {
modalBtns[i].addEventListener('click', updateModal);
}
function updateModal() {
//Get parent div which has data attributes
let parentDiv = this.closest('.modalBtn');
//Get/set attribute data-pkg from parent and set as pkg
let pkg = parentDiv.getAttribute("data-pkg");
//Get/set variables from parent attributes
let price= parentDiv.getAttribute("data-price");
let duration = parentDiv.getAttribute("data-duration");
let desc = parentDiv.getAttribute("data-desc");
let btnImg = parentDiv.getAttribute("data-img");
let modalImg = document.getElementById("modalImg");
//Find hidden form field & name field
let pkgField = document.getElementById("pkg");
let nameField = document.getElementById("name");
//Set default image for modal
let img = "image1.png";
//Find modal ids and replace innerHTML with parent attributes
document.getElementById("modalTitle").innerHTML = pkg;
document.getElementById("modalPrice").innerHTML = price;
document.getElementById("modalDuration").innerHTML = duration;
document.getElementById("modalDesc").innerHTML = desc;
//If img attribute is 'custom' or 'thumbnail' replace it with alternate image
if (btnImg == "custom"){
img = "image2.png";
}
if (btnImg == "thumbnail") {
img = "image3.png";
}
//Set img for modal
modalImg.src = img;
//Set pkg value in form to pkg
pkgField.value = pkg;
}
Wrap your JS Code within function like this:
(function () {
/**
* Put your code here.
*/
})();

how to show text to another div id in another page in javascript?

I have a form where I have submitted the text from the user input but I dont know how to show the text to a different div in a another page in javascript. can anyone help me solve this issue? thanks for the help.
here is my script:
<input onclick="addTheEvent(); return false;" type="submit" value="Add to list" class="btn btn-primary" />
<script>
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candId');
var getCandId = document.getElementById("candId");
var displayCandId = getCandId.options[getCandId.selectedIndex].value;
function addTheEvent() {
addToTheContent.innerHTML = "name = " +
displayCandId + " at " + scheduleEvent.value;
}
</script>
Another page: (I want to add the value to show in my content div that is in another page)
<pre id="content" style="white-space: pre-wrap;"></pre>
You can use a single page application (SPA).
A single-page application is an app that works inside a browser and does not require page reloading during use.
But the SPA is quite a massive theme. It's required for knowledge of the usage browser history, ajax , etc. So you should try to use variant #2
You can use local localStorage of the browser where you can save your data
localStorage.setItem("key","value") //set value into local storage
localStorage.getItem("key") // get value
The "key" is an any string
On another page use
document.addEventListener("DOMContentLoaded", function(event) {
const dataFromLocalStorage = localStorage.getItem('key');
document.querySelector("#content").innerHTML = dataFromLocalStorage; })

Javascript, program not entering function with button clicks

I'm having problems with a startGame function in my code and am seeking help. Originally, I have some HTML code like so:
`
<div id="startScreen">
<h1>Spell and Blade</h1>
<button id="startButton">Start</button>
<!-- Pop-up window -->
<div id="popUpWindow" class="popUpWindow">
<!-- Pop-up window content -->
<div class="popUpWindow-content">
<span class="close">×</span>
<p>
Please select a character type that best fits your play style.
The character type you choose will be the character you control!
</p>
<div id="characterButtons">
<button class="tank" onclick="startGame(1)">Tank</button>
<button class="wizard" onclick="startGame(2)">Wizard</button>
<button class="elf" onclick="startGame(3)">Elf</button>
</div>
</div>
</div>
`
^^This code is embedded in the body tag and the script tags are at the button. This is the main contents of the HTML page.
Calling this function in my javascript labels it undefined when the user clicks any of the characterButtons.
Javascript, name of file Canvas.js:
`function startGame(characterType){
//Code that starts the game.
}`
Other solutions I have tried are in another file called, ButtonProperties.js:
characterButtons.onclick = function () {
console.log("Here in characterButton function");
var characterType = 0;
var tankButton = document.getElementsByClassName("tank");
var wizardButton = document.getElementsByClassName("wizard");
var elfButton = document.getElementsByClassName("elf");
if (tankButton.onclick) {
console.log("Here in tankButton if statement");
characterType = 1;
startGame(characterType);
}
if (wizardButton.onclick) {
characterType = 2;
startGame(characterType);
}
if (elfButton.onclick) {
characterType = 3;
startGame(characterType);
}`enter code here`
}
The above file also has code relating to a pop up window, but I don't think that is where the problem is, also
var characterButtons = document.getElementById("characterButtons"); is near the top of the file, just not listed above.
I'm clueless as to why the function is not getting called. The console.log function counts the number of times a character button is clicked just fine, but the program won't go into any of the if statements. Any help anyone can provide is much appreciated!
You are using getElementsByClassName which returns array, so your buttons tankButton, wizardButton etc are arrays. I would suggest you change your code like below
<div id="characterButtons">
<button id="tank" onclick="startGame(1)">Tank</button>
<button id="wizard" onclick="startGame(2)">Wizard</button>
<button id="elf" onclick="startGame(3)">Elf</button>
</div>
and use
var tankButton = document.getElementById("tank");
var wizardButton = document.getElementById("wizard");
var elfButton = document.getElementById("elf");
then it should work. This is better performance wise as well.

Use button to setAttribute and display it within span tag

I am trying to create a real-world example of get and set data attribute.
so I created a simple div that contains the data-email attribute and set a default one.
Now what I want to attain is when I click on the button it will change the default attribute to the set attribute on my JavaScript codes.
Currently I also don't know how can I show the data attribute value inside tag of my div.
here's my markup:
<div id="my-id" data-email="youremail#email.com">Sam's email is <span> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click-btn()">Set Attribute Now</button>
here's my JavaScript:
var email = document.getElementById('my-id');
var emailget = email.getAttribute('data-email');
var button = document.getElementById('btn-id');
function click-btn(){
emailset = email.setAttribute('data-email', newemail#email.com);
}
here's the JSFIDDLE link: http://jsfiddle.net/jypb2jdg/6/
Any idea?
As #adeneo suggested we should not use hyphen in function name as it may be interpreted as minus sign, so remove and you may use like this:
You need to use quote in setAttribute value:
function clickBtn(){
emailset = email.setAttribute('data-email', 'newemail#email.com');
//^^ here ^^
}
You need something like this:
function clickBtn(){
emailset = email.setAttribute('data-email',
email.getAttribute('data-email') || 'newemail#email.com');
}
First thing is that the email you've written must be within quotes.
<div id="my-id" data-email="youremail#email.com">Sam's email is <span id="my-span-id"> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click_btn()">Set Attribute Now</button>
The JS code:
function click_btn(){
var email = document.getElementById('my-id');
var emailContainer = document.getElementById("my-span-id");
var emailget = email.getAttribute('data-email');
emailContainer.innerText = emailget;
emailset = email.setAttribute('data-email', "newemail#email.com");
}
The code can be found in:
http://jsfiddle.net/jypb2jdg/17/
Some point I want to mention:
Include the JS before the div. Because button will not recognize click_btn() function before its declaration;
Do not use '-' symbol for function names in JS.
You could write a script without using ID for span. It will need additional structs (finding child elements, figuring out which one is what you need, set its' innertext.
You need to keep in mind that functions in javascript cannot have hyphens in their name as it is treated as a mathematical operator. Rest is just plain DOM manipulation :
<div id='my-id' data-email="youremail#email.com">Sam's email is <span id="mail"> "Show Email Here" </span>
</div>
<button type="button" id="btn-id" onclick="clickbtn()">Set Attribute Now</button>
jS:
var em;
window.onload = function(){
em = document.getElementById("my-id");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
};
function clickbtn(){
var old_mail = em.getAttribute("data-email");
em.setAttribute("data-email","newmail");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
}
Fiddle : http://jsfiddle.net/dndnqygL/4/
Note : instead of assigning a new id to the span you can also use the element.firstChild property to set the innerHTML.

Categories

Resources