Adding data to dynamic form - javascript

I am using this dynamic form generation code . https://www.jqueryscript.net/form/dynamic-forms-fields.html#google_vignette
Example : https://www.jqueryscript.net/demo/dynamic-forms-fields/
I have modified the html to take option value as input . I am adding options from an array. I want all the options to be shown from that array , on "Add" new form again the same options should come.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jQuery Dynamic Forms Plugin Example</title>
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.1.3/darkly/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/dynamic-form.js"></script>
<style>
.container { margin: 150px auto; }
h1 { margin-bottom: 50px; }
</style>
<script>
$(document).ready(function() {
var dynamic_form = $("#dynamic_form").dynamicForm("#dynamic_form","#plus5", "#minus5", {
limit:10,
formPrefix : "dynamic_form",
normalizeFullForm : false
});
$("#dynamic_form #minus5").on('click', function(){
var initDynamicId = $(this).closest('#dynamic_form').parent().find("[id^='dynamic_form']").length;
if (initDynamicId === 2) {
$(this).closest('#dynamic_form').next().find('#minus5').hide();
}
$(this).closest('#dynamic_form').remove();
});
});
function addLocation() {
var input_object1 = JSON.parse('[{"id":1,"name":"Pune","facilityType":"CAMPUS","feedback":true,"roomStateMode":2,"asDm":true,"defaultSlotId":3,"timezone":"Asia/Kolk ata","visitorKioskOtpAllow":true,"visitorKioskQrCode":true,"defaultSlotStartBefore":5,"visitorCheckInTemplate":"","visitorPassTemplate":"visitor-pass-horizontal","s howAttendance":true,"employeePassTemplate":"employee-pass-template_1.html","employeePassPreapprovedTemplate":"employee-pass-preapproved-template_1.html","employeePa ssAdminApprovalRequired":true,"employeePassMaxDays":15,"employeePassAllowExternalUsers":true,"employeePassAdminApprovalExternalUsers":true,"attendanceReportTemplate ":1,"visitorQuickCheckInTemplate":"visitor_quick_checkin_email_template.html","level":2,"deskGroupBookingAllow":true,"deskGroupBookingMaxPeople":5,"latitude":18.520 4,"longitude":73.8567,"city":"Pune","streetAddress":"","rosterMax":50,"rosterConfigType":1,"rosterAllowedUptoDays":30,"deskBookIfRoster":false,"disableDeskBookShift Option":true,"healthDeclarationNotificationPreHours":2,"healthDeclarationDeskBookingAutoCancelDays":3,"countryCode":"25","healthDeclarationDisableDeskCheckinWithout Pass":false,"deskBookingKioskQrCodeCheckin":true,"disableDeskBookAmenityOption":true,"deskBookMaxEndDays":10,"deskBookAvailableLevelWise":true,"deskBookingDisableCo worker":false,"deskBookingDefaultDuration":9,"deskBookingCovidVaccinationCertDisable":true,"visitorQuickInviteAllow":true,"visitorQuickInviteTitle":"test","visitorQ uickInvitePurpose":"Other","defaultRoomDisplayTheme":{"id":1,"name":"foo","homeImageId":215,"homeImageChecksum":"7c858c1e9e6c971cc360141e92fc918e","homeFontColor":" e5e0ec"}}]') ;
var input_object2 = JSON.parse('[1,8,11,83,37,88,40,42,41]');
var campush_from_dashboard = null;
// for the edit , it should look for the id
$.each(input_object1, function (index, value) {
if(campush_from_dashboard == null){
if (jQuery.inArray(value.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id
})).text(value.name)
.appendTo('[id^=location]');
}
}
$.each(input_object1[index].facilities, function (index1, value1) {
if (jQuery.inArray(value1.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id
})).text(value.name + value1.name)
.appendTo('[id^=location]');
}
$.each(input_object1[index].facilities[index].facilities, function (index2,
value2) {
if (jQuery.inArray(value2.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id,
"floorId": value2.id
})).text(value.name + value1.name + value2.name)
.appendTo('[id^=location]');
}
});
});
});
};
</script>
</head>
<body>
<div class="container">
<form method="POST">
<label class="form-label">Advanced Properties for Desk Usage Analysis (Optional)</label>
<div class="form-group" id="dynamic_form">
<div class="row">
<div class="col-md-12 ">
<label for="location" class="form-label">Location</label>
<select class="form-select" name="location" id="location" placeholder="Location"
aria-describedby="teamsFeedback" required class="selectpicker" multiple>
</select>
</div>
<div class="button-group mt-2 mb-2 col-12">
<a href="javascript:void(0)" class="btn btn-primary " id="plus5" >Add More Advance Properties</a>
Remove
</div>
</div>
</div>
</form>
</div>
</body>

Related

Why does the live search not show up with live results in this script?

this is the header which contains the search box and the ul in which the live search results should be showing up. It prints the information about the data items out to the console, which means that the data can be found but it doesn't change anything in the ul which is linked to be altered when search results are found. I also checked the jsonSerialize function and it seems to be correct.
<< ? php
//require_once('../Models/AuctionData.php');
require_once('../Models/AuctionDataSet.php');
$auctionDataSet = new AuctionDataSet();
$auctionDataSet = $auctionDataSet - > fetchSearch($_GET["q"]);
echo json_encode($auctionDataSet);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/my-style.css" rel="stylesheet">
<!--<script src="js/Script.js"></script>-->
<title>Auction Website -
<?php echo $view->pageTitle; ?>
</title>
</head>
<body role="" document ">
<div class="container ">
<div class="row ">
<div id="title " class="col-xs-12 ">
<img src="images/iconhead.jpg "/>
<div class="pull-right "> <h1><?php echo $view->pageTitle ?> </h1></div>
</div>
</div>
<div class="row ">
<div id="menu " class="col-xs-6 col-sm-3 col-md-2 ">
<ul class="nav navbar_default nav-stacked ">
<li>Home </li>
<?php if(isset($_SESSION['id']))
{
echo " <li><a href='Logout.php'>Logout</a></li>"; } else{ echo "
<li><a href='Login.php'>Login</a></li>"; echo "
<li><a href='Register.php'>Register</a></li>"; } ?>
<form><input type="text" class="form-control input-lg" id="search" placeholder="search">
</form>
<ul class="list-group" id="txtHint"></ul>
</ul>
</div>
<script type=application/javascript>
document.addEventListener("DOMContentLoaded", readyPage);
function readyPage() {
let searchIn = document.getElementById("search");
searchIn.addEventListener("keyup", showHint);
console.log("ready");
}
function showHint(event) {
const text = event.target.value;
console.log(event);
let xmlhttp = new XMLHttpRequest();
let uic = document.getElementById("txtHint");
if (text.length > 1) {
xmlhttp.open("GET", "Ajax/ajaxSearch.php?q=" + text);
xmlhttp.send();
return;
}
if (text.length < 2) {
uic.innerHTML = "";
return;
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
let uic = document.getElementById("txtHint");
uic.innerHTML = "";
data.forEach(function(obj) {
console.log(obj);
uic.innerText += '<li class="list-group-item"><p>' + 'obj._id' + 'obj._title' + '</p>';
});
}
};
}
</script>
<div id="content" class="col-xs-6 col-sm-9 col-md-10">

Covid-19 error message when country isn't entered isn't matched with API

I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>

Having trouble setting document.getElementById and then sessionStorage.setItem

I am using HTML and JavaScript for a Wi-Fi landing page (called Splash.html). With Splash.html I need to get variable names with document.getElementById and then set name with sessionStorage.setItem. This information is then retrieved by another html page (called Test.html) but when I am redirected to Test.html it replies with "0". I am not an expert but that says to me that the variable names are not being stored properly. Could someone please look at my code and offer some help?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="msapplication-TileColor" content="#0061da">
<meta name="theme-color" content="#1643a3">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<title>
SmartPlay TV
</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="jquery.mCustomScrollbar.css" rel="stylesheet">
<link href="wifi_landing.css" rel="stylesheet">
<script>
var rootPath = "/xxx/";
var defaultImgPath = "/xxx/assets/front/assets/images/products/7.png"
var firstPath = "http://xxx/xxx/";
</script>
</head>
<body>
<div id="login-form-bg-image-tablet">
<img id="back" src="back_5dc4a0740c93eclouds-1586540_960_720.jpg" onerror="this.src = '/xxx/assets/img/tablet.jpg'"></div>
<div class="page">
<div class="page-main">
<div class="row">
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-left">
<div class="row mark-img row-logo">
<div class="col-md-12 mark-img-rect">
<img id="logo" src="logo_5dc4a05f10a24201906271242crop479976885.jpg" onerror="this.src = '/xxx/assets/img/wifilanding-mark.png'"></div>
</div>
<div class="row mark-img row-url">
<div class="col-md-12 mark-mark-rect text-center">
<span id="url" style="word-break: break-word;">www.basicplasticsurgery.com</span>
</div>
</div>
<div class="row">
<div class="col-md-12 textarea-rect" style="display: flex;">
<span id="box_title" class="text3 text" style="padding: 20px 30px; background: white; width: 100%; position: unset; word-break: break-word; border: 2px solid grey;"><p>Welcome to Basic Plastic Surgery!<br><br>Your decision to improve your appearance can be one of the most important investments you make for yourself–and your self-confidence. Our staff take every measure to ensure that you receive the highest quality care in a professional, comfortable environment.</p></span>
</div>
</div>
</div>
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12 landing-right">
<div class="row">
<div class="col-lg-9 col-md-12 col-sm-12 col-xs-12" id="gallery">
<div class="row media-rect">
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload1_5dbb7ff59f88074670796_10219304255335727_5029165459597950976_o.jpg" class="file-rect" id="upload1" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload1_desc">CoolSculpting.
Please see front desk for more info</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload2_5dc4a2905bfdb209508_4516468915805_534071624_o.jpg" class="file-rect" id="upload2" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload2_desc">Me playing soccer.</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload3_5dc4a2976ac89IMG_5313.JPG" class="file-rect" id="upload3" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload3_desc">BPS Background</span>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 col-xs-12 media-ele-wrapper">
<img src="upload4_5dcddf7d5131a20191017_220631.jpg" class="file-rect" id="upload4" onerror="noExitImg(this);">
<div class="textbox-rect text-overflow-ellipsis" style="min-height:80px; display:flex; justify-content:center; align-items:center;">
<span class="title" id="upload4_desc">BPS
Test</span>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-12 col-sm-12 col-xs-12 landing-sign-rect">
<div class="landing-sign-rect-form">
<div class="menu1">
<span id="box_text" style="word-break: break-word;">In order to access the internet we need some information. Please submit the following info to use our wifi network.
If you don't submit information you cannot use our network.</span>
</div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name" style="resize:none;" placeholder="First Name">Full Name</textarea></div>
<div class="form-group ">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_name1" style="resize:none;" placeholder="Last Name">Email</textarea></div>
<div class="form-group">
<textarea class="form-control autosize" onkeydown="resize(this)" onkeyup="resize(this)" rows="1" id="user_email" style="resize:none;" placeholder="Email Address">Tell us what products you're interested in learning about:
</textarea></div>
<div class="form-group text-center">
<!-- <button class = "btn" type = "button" style = "background:#0073c3;color: white;">Sign In</button> -->
<!-- <form method="get" action="$authaction" onsubmit="SubmitFunc()"> -->
<form method="get" action="http://192.168.50.10:2050/nodogsplash_auth/" onsubmit="SubmitFunc()">
<input type="hidden" name="tok" value="$tok"><input type="hidden" name="redir" value="$redir"><input style="background:#0073c3;color: white;" type="submit" value="Sign In"></form>
</div>
<div class="menu3">
Powered by SmartPlay TV
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
It continues with JavaScript section:
<script>
function SubmitFunc() {
sessionStorage.clear();
var name = document.getElementById("user_name").value;
var name1 = document.getElementById("user_name1").value;
var email = document.getElementById("user_email").value;
sessionStorage.setItem("name", name);
sessionStorage.setItem("name1", name1);
sessionStorage.setItem("email", email);
}
function resize(obj) {
obj.style.height = "1px";
obj.style.height = (25 + obj.scrollHeight) + "px";
}
</script>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="jquery.mCustomScrollbar.concat.min.js"></script>
<script src="custom_new.js"></script>
<script src="common.js"></script>
<script src="jquery.validate.js"></script>
<script>
initResize();
function alignTextBox() {
if (jQuery(window).width() < 770) {
jQuery(".media-rect").css("height", "");
jQuery(".textarea-rect .text2").css("min-height", "");
return;
} else {
jQuery(".textarea-rect .text2").css("min-height", "680px");
}
}
function initResize() {
var fileRectObj = jQuery(".file-rect").eq(0);
var width = fileRectObj.width();
var height = width * 9 / 16; // 16:9 to width
jQuery(".file-rect").css("height", height + "px");
alignTextBox();
}
jQuery(window).resize(function() {
initResize();
})
jQuery(document).ready(function() {
jQuery('.autosize').each(function() {
resize(this);
});
});
</script>
</body>
</html>
And here is the Test.html script that includes the getItem part:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Contact Form</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h3 style="margin-top: 100px; text-align: center;">Thank you for your submission. You can now browse the internet freely.</h3>
<script type="text/javascript">
function sendEmail1() {
console.log('sending email');
var name = localStorage.getItem("user_name");
var name1 = localStorage.getItem("user_name1");
var email = localStorage.getItem("user_email");
alert(name + name1 + email);
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'http://192.168.50.10:8000/htdocs/sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {}
};
xhr.send();
}
function sendEmail2() {
console.log('sending email');
var name = localStorage.getItem("name");
var name1 = localStorage.getItem("name1");
var email = localStorage.getItem("email");
var xhr = new XMLHttpRequest();
// xhr.open('GET', 'sendEmail.php?name=john&name1=name1&email=test');
xhr.open('GET', 'sendEmail.php?name=' + name + '&name1=' + name1 + '&email=' + email);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
alert(xhr.responseText);
// return false;
}
};
xhr.send();
}
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
// alert('ready');
// alert(localStorage.getItem("email") + ":" + sessionStorage.getItem("email"));
// alert(sessionStorage.getItem("email") + ":" + localStorage.getItem("email"));
sendEmail1();
});
</script>
</body>
</html>
Test.html is using localStorage instead of sessionStorage.

How to push element in array of JSON

This is my controller from which I am requesting to POST the data on server. While I am able to POST title and rating, i am unable to POST any genres because Genres is an array. How to push the data in Genres Array?
app.controller('addTrack', function ($scope, $http) {
$scope.tracks = [];
var genre = [];
var pushing = genre.push($scope.add_genre);
$scope.add_track = "";
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.tracks = response.data.results;
});
$scope.add = function (event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', {
title: $scope.add_title,
rating: $scope.add_rating,
})
.then(function (data) {
$scope.genres = data;
//console.log($scope.add_genre);
$scope.add_title = '';
$scope.add_rating = '';
$scope.add_genre = '';
});
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.genres = response.data.results;
});
}
} });
Http POST to http://104.197.128.152:8000/v1/tracks
Accepted response
{
"title": "animals",
"rating": 4.5,
"genres": [
1
]
}
Providing you my HTML as well.
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="add_title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="add_genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="add_rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
<div class="clearfix">
<label>Available Tracks</label>
<ul class="list-group" ng-repeat="track in tracks">
<li class="list-group-item clearfix"><span class="pull-left title">{{track.title}}</span> <span class="genre">[{{track.genres[0].name}}]</span> <span class="pull-right rating">{{track.rating}}</span></li>
</ul>
</div>
</div>
</body>
</html>
If what you are trying to achieve is to add a track object with title, rating and genre, you need to change your whole logic so your controller will bind all inputs to the same object properties.
First you need to define a track object in your controller, and bind the inputs to its properties in your HTML:
JavaScript:
app.controller('addTrack', function($scope, $http) {
$scope.tracks = [];
$scope.track = {
title: '',
rating: 0,
genre: ''
};
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function(response) {
$scope.tracks = response.data.results;
});
$scope.add = function(event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', $scope.track)
.then(function(data) {
$scope.track = {};
});
}
}
});
HTML:
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="track.title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="track.genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="track.rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
</div>
</body>
</html>
Note:
Note the use of ng-model="track.title", ng-model="track.rating"
and ng-model="track.genre" in the HTML to bind these inputs to our
trackobject properties.
This code assumes that genre will be a string here, if you will use a
list of object you need to amend your code so it fits this option.

Javascript fix duplicated output

This is my code, everything is working good only when i try to output an array, i get the whole array again and again with the new value each time. But i actually want is to output the whole array as a block below eachother and each time i click on check i get the new value in the array and printed in the left Woorden Geprobeerd list With no duplicated value. Does someone know how i can fix this.
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Lingo spel</title>
<meta name="Lingo" content="Making an lingo project for school">
<meta name="Author" content="Ronald Julian Dewindt">
<meta name="Made Date" content="18-11-2015">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<link href='https://fonts.googleapis.com/css?family=Oswald|Montserrat|Raleway|Poiret+One|Indie+Flower|Dosis' rel='stylesheet' type='text/css'>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="border col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row">
<!--<div class="col-xs-12">
<img src="lingo_logo.jpg">
</div>-->
<div class="col-xs-12">
<label>Typ een eu land hier in:</label>
<input class="form-control input" type="text" id="woord">
<button class="btn btn-primary" type="button" onclick="lingo()">Check</button>
<p style="padding-left:10px; display:inline-block;"><b>punten:</b></p><p style="display:inline-block;" id="punten">0</p>
<p style="padding-left:20px; display:inline-block;"><b>Kansen:</b></p><p style="display:inline-block;" id="kans">30</p>
</div>
<div class="col-xs-5">
<h4>Woorden Geprobeerd</h4>
<p class="try" id="try"></p>
</div>
<div class=" col-xs-3">
<h4>Correcte woord</h4>
<p class="word" id="hiddenWord"></p>
</div>
<script type="text/javascript">
var euLanden = new Array('Nederland','Belgie','Bulgarije','Cyprus','Denemarken','Duitsland','Estland','Finland','Frankrijk','Griekeland','Ierland','Italie','Luxemburg','Malta','Oostenrijk','Polen','Spanje','Zweden','Hongarije','Kroatie','Letland','Litouwen','Portugal','Roemenie','Slovenie','Tsjechie');
var random = euLanden[Math.floor(Math.random() * euLanden.length)];
var woordenTry= new Array();
var tryOutput = "";
var punten= 0;
var kans= 30; document.getElementById("hiddenWord").innerHTML="?".repeat(random.length);
function lingo(countryName, textInput)
{
textInput = document.getElementById("woord").value;
textInput = textInput.toLowerCase();
countryName = random.toLowerCase();
var output = "";
for(var i=0; i< countryName.length; i++)
{
if(textInput.indexOf(countryName[i])!== -1)
{
output += countryName[i];
}
else
{
output += "?";
}
}
woordenTry.push(output);
for(w=0; w<woordenTry.length; w++)
{
document.getElementById("hiddenWord").innerHTML=output;
tryOutput+= woordenTry[w] + "<br>";
document.getElementById("try").innerHTML=tryOutput;
}
if(textInput != countryName)
{
kans--;
}
if(kans == 0)
{
alert("U heeft verloren, Probeer opnieuw");
location.reload();
}
if(textInput === countryName)
{
random = euLanden[Math.floor(Math.random() * euLanden.length)];
random.length
alert("Je hebt het woord gevonden");
punten++;
alert("Zoek het nieuw woord op!");
document.getElementById("hiddenWord").innerHTML="?".repeat(countryName.length);
}
document.getElementById("punten").innerHTML=punten;
document.getElementById("kans").innerHTML=kans;
}
</script>
</div>
</div>
</div>
</body>
</html>

Categories