Passing value of check boxes to Javascript from HTML embedded in PHP - javascript

Good afternoon. I am trying to pass the values associated with a list of checkboxes to a javascript function that then calculates the total for all values associated with selected checkboxes.
The HTML code is embedded within PHP. When I try to call the javascript function, I get a null result. Could anyone provide some pointers on where I am going wrong. Code below. All help is appreciated! Thank you.
The variables are pulled from the results of an SQL query executed just before the copied code below.
"<form action = 'book.php' method = 'POST'>
<tr><td>$seat</td>"
."<td>$zone</td>"
."<td>$price</td>"
."<td><input type = 'checkbox' id = 'seat['$seat']' value = '$price'></td></tr>"
//."<input type = 'hidden' id = '$seat' value = '$price' action = 'checkDetails()'>"
;
}
echo "</table>"
."Email address for booking ".
"<input type = 'text' name = 'email id'>"
."  "
."<button type = 'submit' name = 'book' action = 'book.php'>Book</button></form>"
."  "."<button name = 'check price' onclick = 'checkDetails()'>Check Prices</button>";
}
catch (PDOException $e) {
echo "PDOException: ".$e->getMessage();
}
echo "<script language = 'javascript'>
function checkDetails() {
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {
if (seat[i].checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total);
}
}
}
</script>";

You are looping through the forms length.
Since this is rendered in php why dont you set the length of of I programmatically
var i;
var length = <?= $seat?>;
for (i = 0; i < length; i++) {
if ( document.getElementById('seat[i]').checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total.value);
}
the following code is looping through the form and not the elements
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {

Related

A function to return 3 random profiles from JQuery?

I would like to create a web app that returns 3 random profiles of student that are randomly assigned to you once you click a button.
I am looking for un function that does that but I can't find anything. Do you have anything that does the job?
Here is the Github repository if you need it.
All I've tried function(randomusers) but I failed
$.getJSON("https://randomuser.me/api/", function (randomusers) {
var user = randomusers.results[0];
document.getElementById("prenom").textContent = (user.name.first); //prénom
document.getElementById("adresse").textContent = (user.location.street + " " + user.location.city + " " + user.location.state); // adresse
document.getElementById("email").textContent = (user.email); //email
var img = document.createElement('IMG'); //profile picture
img.setAttribute('src', user.picture.large);
document.getElementById("photo").appendChild(img);
}
I want 3 random user profiles to appear when I click the "find my partners" button. Unfortunately, I am not able to display these 3 profiles and anything for the record. Is it that I didn't link the button to the JS function or that the function is wrong?
I am new to coding and I was a bit too ambitious so I have no clue how to do it now.
Thanks a lot for your help
There are multiple ways to display this in both JavaScript and in JQuery.
You can find the working code sample in this git repository
https://github.com/helloritesh000/DisplayRandom3Profile
Call function GetRandomProfiles() on click on button Find My Partners. This will load 1 profile at a time keep clicking the button it will load the another profile.
<script type="text/javascript">
function GetRandomProfiles()
{
$.getJSON( "https://randomuser.me/api/", function( randomusers ) {
var user = randomusers.results[0];
// document.getElementById("picturegenerator").innerHTML = "";
var img = document.createElement('IMG');
img.setAttribute('src', user.picture.large);
document.getElementById("picturegenerator").appendChild(img);
var detail = document.createElement('div');
detail.innerHTML = "";
var prenom = document.createElement('div');
prenom.setAttribute('id', 'prenom');
prenom.innerHTML = user.name.first;
detail.innerHTML += prenom.outerHTML;
var adresse = document.createElement('div');
adresse.setAttribute('id', 'adresse');
adresse.innerHTML = user.location.street +" "+ user.location.city + " " + user.location.state;
detail.innerHTML += adresse.outerHTML;
var email = document.createElement('div');
email.setAttribute('id', 'email');
email.innerHTML = user.email;
detail.innerHTML += email.outerHTML;
document.getElementById("picturegenerator").appendChild(detail);
} );
}
</script>
Another way to achieve is just add the server call in a for loop which runs 3 times. It will pull 3 profiles in single button click.
<script type="text/javascript">
function GetRandomProfiles()
{
for(i=0; i<3;i++)
{
$.getJSON( "https://randomuser.me/api/", function( randomusers ) {
var user = randomusers.results[0];
// document.getElementById("picturegenerator").innerHTML = "";
var img = document.createElement('IMG');
img.setAttribute('src', user.picture.large);
document.getElementById("picturegenerator").appendChild(img);
var detail = document.createElement('div');
detail.innerHTML = "";
var prenom = document.createElement('div');
prenom.setAttribute('id', 'prenom');
prenom.innerHTML = user.name.first;
detail.innerHTML += prenom.outerHTML;
var adresse = document.createElement('div');
adresse.setAttribute('id', 'adresse');
adresse.innerHTML = user.location.street +" "+ user.location.city + " " + user.location.state;
detail.innerHTML += adresse.outerHTML;
var email = document.createElement('div');
email.setAttribute('id', 'email');
email.innerHTML = user.email;
detail.innerHTML += email.outerHTML;
document.getElementById("picturegenerator").appendChild(detail);
} );
}
}
</script>
Well, you have to do three tasks, and you can do it by using pure JavaScript.
Get 3 random users from the API URL (https://randomuser.me/api/) through HTTP request.
Collect the random user data in an array.
Print the HTML with the proper contents from the array that you have.
With pure JavaScript:
You need to create a helper function to do asynchronous HTTP requests (AJAX). This is a very basic structure for any web project with JavaScript to do asynchronous HTTP requests without any third party library like jQuery. This helper function is kinda similar to $.get(), $.getJSON(), $.ajax() functions in jQuery.
var newXHR = null;
function sendXHR(type, responseType, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.responseType = responseType;
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response); // Anonymous function is required at this point: function(argument) { ... }.
}
};
}
Note:
You can not use a for loop statement with asynchronous requests
because the results can be obtained at an undetermined time, while the
execution of a for loop is synchronous. In that sense, it is
quite useful to use a callback function that allows the
continuation of the execution of your code when the previous execution
ends in a recursive function with asynchronous requests.
Then:
You may create a recursive function with three parameters: url, times, callback. Where:
url. It's a string that is the API URL: https://randomuser.me/api/.
times. It's a number. In this case is 3, because you need to do 3 HTTP requests to the API URL.
callback. It's a function reference to execute passed as parameter. Its value must be a function. This function reference can receive a value as parameter.
The count and arrayOfUsers variables must be defined in the global scope.
function getUsers(url, times, callback) {
if (count < times) { // Check the limit in the recursive process. You need to execute this function only 3 times to get 3 random users from the API URL.
sendXHR("GET", "json", url, null, function(response) { // The response parameter contains the data from the API URL, so you can store this value in an array for every request.
arrayOfUsers.push(response); // Save the random user data from the API in the array.
count++; // Increment the counter.
getUsers(url, times, callback); // Keep executing the function to get more random user data.
});
} else {
callback(arrayOfUsers); // Once reaching the limit return the result of arrayOfUsers through the callback function.
}
}
To store random user data obtained from the HTTP request, you can use Array#push: In this case: arrayOfUsers.push(response);.
A more practical way to build an HTML markup with data is by concatenating strings.
In this case, I have this function:
function renderUsers(data) {
var html = "", len = data.length, user;
for (var i = 0; i < len; i++) {
user = data[i];
html += "<div class=\"user\"><div><label>Name: </label><span title=\"";
html += "LastName: ";
html += user.results[0].name.last;
html += "\">";
html += user.results[0].name.first;
html += "</span></div><div><label>Address: </label><span>";
html += user.results[0].location.street;
html += " ";
html += user.results[0].location.city;
html += " ";
html += user.results[0].location.state;
html += "</span></div><div><label>Email: </label><span>";
html += user.results[0].email;
html += "</span></div><div><label>Image: </label><span>";
html += "<img alt=\"";
html += user.results[0].picture.large;
html += "\" src=\"";
html += user.results[0].picture.large;
html += "\" /></div></div>";
}
return html; // Return the built html.
}
You would have something like this:
(function() {
// Declaring global variables.
var newXHR = null, arrayOfUsers = [], count = 0;
// Helper function to make HTTP requests (AJAX) with JavaScript.
function sendXHR(type, responseType, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.responseType = responseType;
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response);
}
};
}
// Recursive function to get random users.
function getUsers(url, times, callback) {
if (count < times) { // Check the limit in the recursive process. You need to execute this function only 3 times to get 3 random users from the API URL.
sendXHR("GET", "json", url, null, function(response) { // The response parameter contains the data from the API URL, so you can store this value in an array for every request.
arrayOfUsers.push(response); // Save the random user data from the API in the array.
count++; // Increment the counter.
getUsers(url, times, callback); // Keep executing the function to get more random user data.
});
} else {
callback(arrayOfUsers); // Once reaching the limit return the result of arrayOfUsers through the callback function.
}
}
// Function to render in the page with the random users.
function renderUsers(data) {
var html = "", len = data.length, user;
for (var i = 0; i < len; i++) {
user = data[i];
html += "<div class=\"user\"><div><label>Name: </label><span title=\"";
html += "LastName: ";
html += user.results[0].name.last;
html += "\">";
html += user.results[0].name.first;
html += "</span></div><div><label>Address: </label><span>";
html += user.results[0].location.street;
html += " ";
html += user.results[0].location.city;
html += " ";
html += user.results[0].location.state;
html += "</span></div><div><label>Email: </label><span>";
html += user.results[0].email;
html += "</span></div><div><label>Image: </label><span>";
html += "<img alt=\"";
html += user.results[0].picture.large;
html += "\" src=\"";
html += user.results[0].picture.large;
html += "\" /></div></div>";
}
return html; // Return the built html.
}
var btnFindMyPartners = document.getElementById("btnFindMyPartners");
btnFindMyPartners.onclick = function() {
var users = document.getElementById("users");
users.removeAttribute("hidden");
users.textContent = "Loading...";
arrayOfUsers = []; // Reset array of users.
count = 0;
getUsers("https://randomuser.me/api/", 3, function(data) {
document.getElementById("users").innerHTML = renderUsers(data);
});
};
}());
body {
font-family: "Segoe UI", sans-serif;
font-size: 0.8em;
}
button {
border: #819bc2 solid 1px;
cursor: pointer;
}
#users,
#users .user,
#users .user div,
button {
border-radius: 5px;
margin: 5px;
padding: 5px;
}
#users {
border: #819bc2 solid 1px;
}
#users .user {
background-image: linear-gradient(to left, #cfcee6, #fff);
border: #46628c solid 1px;
box-shadow: inset #92979c 0 0px 20px 0px;
}
#users .user div {
border: #d4dbe7 solid 1px;
}
<button id="btnFindMyPartners">Find my partners</button>
<div id="users" hidden>
</div>
I would like to remind you of the following when you build HTML markup dynamically.
HTML5 - The id attribute:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
Hope this helps a little bit more.

Use of variables

I am new on web coding. I use weebly drag and drop but also HTML to add extra things. What I did is has created a variable that includes customers' selections about a product. I would like to add this variable.value to the specific products' short description.
Any help will be appreciated.
Here is my code for to get this variable from another page so final step is to get this variable from product page, short-description section.
Thanks
Tim
<html> <body> <script>
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
for (var i = 0; i < queries.length; i++) {
document.write(queries[i] + "<br>");
}
</script> </body> </html>
If you already have the variable set, just use this in your script
document.getElementById("TheIdOfTheDiv").innerHTML = TheVariable;
The below js fiddle link might help you to easily decode the url
https://jsfiddle.net/bachiavinash/rc3LsjLo/
js code:
function dispnameval(){
var $input = document.f1.t1.value;
var $output = "";
var $inurl = $input.split("?");
var $ary = $inurl[1].split("&");
var $arylen = $ary.length;
var $start = $input.indexOf("?");
var $end = $input.indexOf("=");
//var $output = $input.substring($start,$end);
//$output = $ary[0];
for($i=0; $i<$arylen; $i++){
//alert($ary[$i]);
$output+=$ary[$i]+"<br/>";
}
document.getElementById("output").innerHTML=$output;
}
function clearnameval(){
document.f1.t1.value = "";
document.getElementById("output").innerHTML="";
}

How to send html email line by line using google apps script and google sheet data

I have a script to send an email line-by-line. The problem I have is that I cannot use the data in the current line iteration in an email template. I know how to call functions from the template though in this case I cannot call the function that is being evaluated.
My solution was to create another function that would loop through the data again and send the line instance in an email then break. The problem is that now it takes to long to loop through the lines twice when im sure it can be done once.
I hope i made sense.
Code.gs
function sendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('EmailList');
// get the data as an array
var data = sheet.getDataRange().getValues();
// Loop over each line
for (var i = 1; i < data.length; i+=1) {
// Check the status of the email
if (data[i][4] != 'Sent') {
// get html file content
var html = HtmlService.createTemplateFromFile('Index').evaluate().getContent();
// send the email
MailApp.sendEmail({
to: data[i][2],
subject: 'Hi ' + data[i][0],
htmlBody: html
});
// Set the status to sent
sheet.getRange(i + 1,5).setValue('Sent');
}
} // end for
} // end function sendMail
function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('EmailList');
// get the data as an array
var data = sheet.getDataRange().getValues();
// Loop over each line
for (var i = 1; i < data.length; i+=1) {
// Check the status of the email
if (data[i][4] != 'Sent') {
var firstName = data[i][0];
var lastName = data[i][1];
var email = data[i][2];
var message = data[i][3];
break;
}
} // end for
var returnData = [firstName, lastName, email, message];
return returnData;
} // end function getData
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<? var data = getData(); ?>
</head>
<body>
Hi <?= data[0];?> <?= data[1];?> , with email address <?= data[2];?>
I have a message for you:
<?= data[3];?>
</body>
</html>
You need to read this pushing variables to templates
Your Code.gs
for (var i = 1; i < data.length; i+=1) {
// Check the status of the email
if (data[i][4] != 'Sent') {
var firstName = data[i][0];
var lastName = data[i][1];
var email = data[i][2];
var message = data[i][3];
var returnData = [firstName, lastName, email, message];
var html = HtmlService.createTemplateFromFile('Index');
html.data = returnData ;
var template = html.evaluate().getContent();
// send the email
MailApp.sendEmail({
to: data[i][2],
subject: 'Hi ' + data[i][0],
htmlBody: template
});
// Set the status to sent
sheet.getRange(i + 1,5).setValue('Sent');
}
Your Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Hi <?= data[0];?> <?= data[1];?> , with email address <?= data[2];?>
I have a message for you:
<?= data[3];?>
</body>
</html>
Here is the strategy I would use in order to cut down on the processing time. First get all the data that you want to inject into the HTML. Then get the HTML from the file just once, and put it outside of the for loop. Then construct new HTML to be injected into the original HTML for every loop. You will need to use string formulas, and concatenate text to dynamically change the HTML.
You won't look up the data from the spreadsheet on every loop, or have the templated HTML evaluate the HTML on every loop. You'll get the data once. It will be store in an array. You'll get the HTML once, and it will be stored in a variable.
You'll need to use JavaScript string methods to manipulate the HTML.

Javascript To PHP Source Code Conversion

I want to convert the following client side javascript code to server side PHP in order to protect some code. Below is a sample code of what I would like to have in PHP (and not using echo on each line, as this does not hide anything apart from the opening and closing PHP tags!)
function calc() {
var aa = document.a.lsofa.value * 40.77;
var bb = document.a.ssofa.value * 29.26;
var z90 = "Text here.";
var ctt = aa + bb;
ctt = parseInt(ctt);
tot = ctt;
if (tot < 1) {
var rslt = "Please enter relevant quantities in the form above.";
}
else {
var rslt = "Complete. We would require " + ctt.toString() + z95 + "";
}
document.a.answer.value = rslt
Also the onclick event of the form would need to be changed (I would like to keep the converted code on the same page an just call this function on form submit).
Any help would be appreciated.
You mean something like this:
header('Content-type: application/json');
$aa = $_GET["lsofa"] * 40.77;
$bb = $_GET["ssofa"] * 29.26;
$z90 = "Text here.";
$ctt = aa+bb;
$ctt = intval(ctt);
$tot = $ctt; // not useful
if ($tot<1) {
echo json_encode(array('result' => "Please enter relevant quantities in the form above."));
} else {
echo json_encode(array('result' => "Complete. We would require " . $ctt . $z95));
}
called with
$(function() {
$("#myForm").on("submit",function(e) {
e.preventDefault(); // stop submission
$.get("calc.php",$(this).serialize(),function(data) {
alert(data.result);
});
});
});

perform a search of database with multiple textboxes

I'm trying to perform a search of database when user enters a persons name into textbox. The texboxes are dynamic, so whenever the user enters a number into the "No. of firemen on scene" textbox as seen in the snap shot below, the same amount of textboxes appear in the fieldset below under("List of firemen on scene").
However, my problem is that whenever I'm trying to perform the search, the search is only performed on the first textbox and not on the others. Could anyone assist me as to highlighting and/or explaining what the problem(s) may be?
occurrence.php
<label>List of Firemen On Scene</label><br>
<div class="NewlyCreatedSelectBoxes" name="firemen_list"></div>
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName` FROM `firefighterinfo` WHERE `firstName` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['firstName'], ' ', $results_row['middleName'], ' ', $results_row['lastName'], '</p>';
}
}
}
?>
search.js
function firemanAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes").val();
$('.NewlyCreatedSelectBoxes').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" id="search" required/><br>';
}
$('.NewlyCreatedSelectBoxes').append(txtBox);
$('#search').keyup(function () {
var search_term = $(this).val();
$('#search_results').html('Searching database...');
if (search_term !== '') {
$.post('php/fireman_search.php', { search_term: search_term }, function (data) {
$('#search_results').html(data);
});
} else {
$('#search_results').html('Not Found');
}
});
return false;
}
Since the other field is dynamic, you'll need to use event delegation on the search inputs. Also, you're adding elements with duplicate ID's, which is bad. ID's have to be unique, just use classes for this:
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" class="search" required/><br>';
}
Change:
$('#search').keyup(function () {
To:
$(".NewlyCreatedSelectBoxes").on("keyup", ".search", function() {

Categories

Resources