Page won't display after clicking alert box - function

Creating a game where the user answers 5 questions. I want to display their score on a separate page when then complete the game.
This is how my page is set up:
<div data-role="page" id="displayScore">
<div data-role="header">
<h1>How Did You Go?</h1>
</div>
<div data-role="content">
<p id="displayScore" align="center"></p>
<input type="button" value="Play Again?" onClick="startGame();"/>
<input type="button" value="Main Menu" onClick="" />
</div>
<div data-role="footer">
<h4>AL</h4>
</div>
</div>
</body>
</html>
This is my function:
function score()
{
ans += "You scored <strong> " + score + " </strong> out of <strong> " + count + "!</strong>";
document.getElementById('displayScore').innerHTML = displayScore;
}

if you want to pass value to another page then you have to do one of the method between the following methods
pass the value by query string (using get method)
pass the value by post method
use cookies, localStorage or sessionStorage to store the value and retrieve the value in the another page.
if you want to open up a new window the the code will be like this
window.open('http://www.google.com','GoogleWindow', 800, 600);
if you want to create a new window with dynamic value then
<html>
<body>
<script>
myWindow=window.open('','','width=200,height=100');
var displayScore = "your score";
myWindow.document.write("<p> + displayScore + </p>")
myWindow.focus();
</script>
</body>
</html>
it is the best way to directly open the new window with score.
if you have a result.html page then you can pass the score by query string or you can write the javascript code in the result.html page to access any of the cookies, localStorage or sessionStorage to get the score. but make sure you have saved your score in any of it.

Related

Nodejs Stripe how to dynamically pass the Stripe price ID to my server after clicking the purchase button of an item

I am working on my first dynamic website using HTML, Express & node.js. Reading through the Stripe documentation and other sources I've come across various examples but my main goal is to use my Stripe API key and each item price ID's in my server and not in my front end code so no one can temper with them. I've successfully use my Stripe API key on my backend and used the .post method to redirect the user after pressing the Buy Now button to the checkout page as shown below:
Node.js
const stripe = require('stripe')('sk_test_key');
const express = require('express');
const app = express();
app.use(express.static('public'));
const YOUR_DOMAIN = 'http://localhost:4242';
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
line_items: [
{
price: 'price_priceKey',
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.redirect(303, session.url);
});
app.listen(4242, () => console.log('Running on port 4242'));
HTML
<!DOCTYPE html>
<html>
<head>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT"
crossorigin="anonymous"
/>
<title>Product Page</title>
<link rel="stylesheet" href="style.css" />
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<div class="row">
<div class="col-lg-6">
<section>
<div class="product">
<img
class="collar-img"
src="image"
alt="product-image"
/>
<div class="description">
<h3>Leather Collar</h3>
<h5>$9.99</h5>
</div>
</div>
<form action="/create-checkout-session" method="POST">
<button type="submit" id="checkout-button">Checkout</button>
</form>
</section>
</div>
<div class="col-lg-6">
<section>
<div class="product">
<img
class="collar-img"
src="image2"
alt="product-image2"
/>
<div class="description">
<h3>Comsos Collar</h3>
<h5>$19.99</h5>
</div>
</div>
<form action="/create-checkout-session" method="POST">
<button type="submit" id="checkout-button">Buy Now</button>
</form>
</section>
</div>
</div>
</body>
</html>
My problem is I've only figure how to hardcode the price ID for a product inside my line_items object in node.js so when the user clicks the Buy Now button it will only add to the checkout page the items that I added. I've come across examples of adding the price ID to the attribute "data-price-id" inside each button element so that each item has a button that contains its correct price but that exposes all my price ID's to my frontend code. I already tried hiding the ID in my frontend using EJS and the dotenv module in node.js but this was futile. I would really appreciate if someone could point me the right direction or sample code on how to pass these different price ID's after user clicks on each button of each item back to my server.
It's okay to expose the Price IDs to the front-end code. Nobody can do anything with those Prices without access to your API keys, so it's okay if they show up on the front-end.
That being said, you can dynamically pass an ID from back-end to front-end via a number of different methods. The one I would recommend would be document.querySelector()[0]. This allows you to dynamically set an HTML element's value using Javascript.
An example might look like this: document.querySelector("#price-id").value = somePriceID;
The above snippet looks for an HTML element called price-id and assigns the value from the somePriceID variable to it.
[0] https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
I see you're not using a DB.
One approach you could make is just create an object on the server such as:
const PRODUCT_IDS = {
toaster-x1000: {
price_id: 'toaster-price-id'
}
};
That way, you can just use your own codes on the HTML sites and find the Stripe code on the backend when you need it.
For example, if they want the toaster, you would send "toaster-x1000" and just grab that ID from the list:
const ID_RECEIVED = "toaster-x1000";
const CORRECT_STRIPE_ID = PRODUCT_IDS[ID_RECEIVED].price_id;
That would give you the price id you need for the API call.

How to post SQL values into checkboxes

First of all, my question might be a duplicate question to this one: Need html checkbox to be checked by mysql result but I do not understand the answer - the op didn't post any code and I don't see how to fit the suggested code into my case because I need to get the values from SQL (?).
Here all the data:
I have an HTML form with checkboxes, which stores the values as for checked as "1" and unchecked as "0" into an SQL database on submit of the form. Now I want to make it so that it (on page load) pulls data from database and populates the form's checkboxes when the same user comes back to the page. (I know my code is faulty in some places, I still need to resolve quite some things on this project) for right now, what I want to solve is to get the SQL to output the result to existing HTML checkboxes (not create new checkboxes or new HTML form).
Note: my HTML form and my php form are in two separate files and they cannot be merged (I don't know if that makes a difference).
All checkboxes in the form are empty by default. I am using Ajax in my form so that on pageload the userid is passed to a php file which then runs the SQL Query to pull up "1" if the checkbox should be checked and "0" if it should be left unchecked.
Here the piece of HTML which is relevant to the case:
<input type=text id="userid" name="userid" value="">
</div>
<div class="grid">
<div>
<div class="grid-item">
<img src="image.png" alt="">
</div>
<div class="grid-item-title">
<h2>Title</h2>
</div>
<div class="grid-item">
<p>
<input type="hidden" name="owns[item1]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">I own this<br>
</p>
</div>
</div>
<div>
<div class="grid-item">
<img src="image.png" alt="">
</div>
<div class="grid-item-title">
<h2>Title 2</h2>
</div>
<div class="grid-item">
<p>
<input type="hidden" name="owns[item2]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">I own this<br>
</p>
</div>
</div>
This is the Ajax code I am using:
document.addEventListener("DOMContentLoaded", function myFunction() {
var x = 3 //replace with user ID
$.ajax({
url: 'libraryRequest.php',
method: "post",
data: {"userid": x }, // sends id to PHP
dataType: "html",
async: false,
success: function(data){
$('#content').html(data); // currently this overwrites all HTML on the page...
},
error: function (xhr, ajaxOptions, thrownError) {
var errorMsg = 'Ajax request failed: ' + xhr.responseText;
$('#content').html(errorMsg); // currently this overwrites all HTML on the page...
}
})
});
And this is the PHP code I managed to put together sofar:
$userid = 0;
$userid = $_POST['userid'];
if ($userid != 0) { //only execute if there is a user id
$userquery = "SELECT * FROM libraryG WHERE userid =$userid"; //find if userid exists
$result = mysqli_query($con, $userquery);
if(mysqli_num_rows($result)>0) { //if user id exists run this code to pull the data
$sqlupdate = "SELECT * FROM libraryG WHERE userid = $userid";
mysqli_query($con, $sqlupdate);
if ($result->num_rows > 0) {
while($row = $result->fetch_row()) {
print json_encode($row); // edited
}
} //if user id doesn't exist in db or there is no user id - do nothing
}
Each checkbox value is stored in a separate column in SQL.
I have been on this for hours now but in most cases the similar questions I found are explaining solutions for C# or ASP which I have never used and being kinda new in everything I try to avoid those things I don't know anything about if there is a way to do it otherwise.

Update table cell value dynamically using angular6

I am working with an angular 6 application, in the HTML template I have some code as per below, just showing the table cell part of the array, also the table is built using divs.
<div class='table_small'>
<div class='table_cell'>Status</div>
<div class='table_cell'>
<p class="status" >{{incomingData.status}}</p>
</div>
</div>
Please note here that "data" is an array (*ngFor) and is being used in row data and there are multiple data in the table.
Now I have a situation wherein there is a button inside the table rows to cancel the particular order, when the user clicks in, a pop up/modal asks for user confirmation, if the user opts for 'Yes' it would change the status field value to "cancellation is in process" temporarily before it hits the service, once there is a successful response from the customer it would change the station to "cancelled".
I am really not sure how to do the cancellation within the table cell here, if anyone can give insight on this please do.
Thanks
You could pass the element to the function and edit its status:
<div class='table_small'>
<div class='table_cell'>Status</div>
<div class='table_cell'>
<p class="status" >{{incomingData.status}}</p>
</div>
<div class='table_cell'>
<button (click)="showCancelModal(incomingData)"> Cancel</p>
</div>
</div>
And then in the component something like this:
showCancelModal(incomingData) {
// logic for showing modal and retrieving user response
if( response === 'yes') {
incomingData.status = 'Cancel in progress';
yourService.cancel(incomingData)
.pipe( finally(() => incomingData.status = 'Cancelled') )
.subscribe();
}
}

Form with select and text options

I have an HTML form that needs to collect information entered into a text box as well as options that are chosen from a set of dropdown menus. To give a little context, I am creating virtual machines that can be configured by the user on a web page. They must enter a name (arbitrary) and a hostmachine in two separate boxes in addition to selecting options from three different dropdown menus. Because I am working with clusters, there could be as many as 99 "rows" of dropdown menus representing different system configurations that will be a part of the cluster.
Is it possible (if so, advisable?) to have both the text fields and the dropdowns contained in one form? If not, how do I make sure that the submit button sends all the data to my Django server for processing as I need all of this information to ultimately come to the same place.
I currently have them in different forms, but just ignore this for now as it doesn't do anything at the moment. Also don't worry about the lack of dropdowns present in this code as the addSelect() JS function is fully functional. Just know that each added node is given a unique name (node1, node2, etc.) and goes into the div "nodes".
<body><b>Virtual Cluster Initialization</b><br></br>
<div id="container">
<div id="general">
<form method="POST" id="naming">Cluster name:<br>
<input type="text" name="cluster_name">
<br>
Host Machine:<br>
<input type="text" name="host_machine">
</form>
</div>
<form method="POST" id="node_config"></form>
<div id="nodes" form="node_config"></div>
<div id=node1">
<select name="node_type" id="node_type">Node Type</option>
(two options go here)
<select name="issp_version" id="issp_version>ISSP Version</option>
(7 or so options go here)
<select name="os" id="os">Operating System </option>
(about 20 options)
<button id="add" onclick="addSelect('nodes');">+</button>
</div>
<br></br><input type="submit"></input>
</body>
EDIT1: Added the an example dropdown for clarity. Would it be better to NOT make a new div for each node? I did this initially because it seemed like a good way to keep each node's configuration separate. Like I said, there could be up to 99 nodes, each with three dropdown menus.
Not really sure if I understand what you're asking. Showing us the code after your drop downs are added would help. Syntax wise, this wont work. Inputs should be inside forms and div doesn't have a form property.
Put everything into one form if you want it to all be in one post. If your dynamically adding new form elements you can use an array as element names.
How about something like this?
<script>
var nodeID = 0;
function addSelect() {
var html = "<div id='node_" + nodeID + "'>";
html += "<select name='node_type[" + nodeID + "]' id='node_type'><option>example</option></select>";
html += "<select name='issp_version[" + nodeID + "]' id='issp_version'><option>ISSP Version</option></select>";
html += "<select name='os[" + nodeID + "]' id='os'><option>Operating System </option></select>";
html += "</div>";
document.getElementById('nodes').innerHTML += html;
nodeID++;
}
</script>
<div style="margin-bottom:20px;"><b>Virtual Cluster Initialization</b>
</div>
<form>
<div id="container">
<div id="general">
<div>Cluster name:</div>
<div>
<input name="cluster_name" type="text">
</div>
<div>Host Machine:</div>
<div>
<input name="host_machine" type="text">
</div>
</div>
<div id="nodes">
<div>Nodes</div>
<div id="node_0">
<select name="node_type[0]" id="node_type"><option>example</option></select>
<select name="issp_version[0]" id="issp_version"><option>ISSP Version</option></select>
<select name="os[0]" id="os"><option>Operating System </option></select>
</div>
<div id="node_1">
<select name="node_type[1]" id="node_type"><option>example</option></select>
<select name="issp_version[1]" id="issp_version"><option>ISSP Version</option></select>
<select name="os[1]" id="os"><option>Operating System </option></select>
</div>
</div>
<div>
<button type="button" id="add" onclick="addSelect();">+</button>
</div>
</div>
<div>
<input type="submit">
</div>
</form>
Here is a JSfiddle to help you visualize what this does:
https://jsfiddle.net/fdss08w9/2/
Example of how you might use this in Django:
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# Get the number of nodes we added
for id, node_type in enumerate(form.cleaned_data['node_type']):
issp_version = form.cleaned_data['issp_version'][id]
os = form.cleaned_data['os'][id]
#do stuff with node_type, issp_version, os

Angular JS - Having an empty array

I have a form that submits data into a function called ng-submit="newBirthday() this pushes data - $scope.bdayname, $scope.bdaydate; into an array called bdaes
My issue is that with all of the tutorials I have seen the array has predefined data is there a way that it can be an empty array that gets filled with data when it is submitted?
app.js:
var app = angular.module('birthdayToDo', []);
app.controller('main', function($scope){
// Start as not visible but when button is tapped it will show as true
$scope.visible = false;
// Create the array to hold the list of Birthdays
$scope.bdays = [{}];
// Create the function to push the data into the "bdays" array
$scope.newBirthday = function(){
$scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});
$scope.bdayname = '';
$scope.bdaydate = '';
}
});
HTML:
<body ng-app="birthdayToDo" ng-controller="main">
<div id="wrap">
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Birthday Reminders</h1>
</div>
<ul ng-repeat="bdays in bdays">
<li>{{bdae.name}} | {{bdae.date}}</li>
</ul>
<form ng-show="visible" ng-submit="newBirthday()">
<label>Name:</label>
<input type="text" ng-model="bdayname" placeholder="Name"/>
<label>Date:</label>
<input type="date" ng-model="bdaydate" placeholder="Date"/>
<button class="btn" type="submit">Save</button>
</form>
</div>
<div id="push"></div>
</div>
<div id="footer">
<div class="container">
<a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a>
</div>
</div>
<script type="text/javascript" src="js/cordova-2.5.0.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
Okay, there were a few of small issues.
An empty array must have no items; [{}] is an array with one item: an empty object. Changing to [] gets rid of the extra bullet.
The bigger issue was your ngRepeat. You used ng-repeat="bdays in bdays". What ngRepeat does is take an array and allow you to do a "for each" on the array, assigning each value to that temporary local variable. You named them the same. Instead, ng-repeat="bday in bdays" will add the DOM nodes inside of it for each item in bdays, giving you a local variable called bday to use to reference each item.
Inside the ngRepeat template, you used bdae, which doesn't reference anything.
I don't know what app.initialize() is, so I removed it. It was just erroring out in the console.
Here's a fixed Plunker: http://plnkr.co/edit/OFWY7o?p=preview