“Undefined index: itemdetails” when sending JSON object from JavaScript to PHP - javascript

Upon entering the quantity of an item and clicking the Add to Cart button the toShoppingCart() method is executed. This method will get the values of labels and text fields and insert them into a JSON object and pass it to the Order.php file.
When sending the JSON object from JavaScript to PHP it returns an error:
Undefined index: itemdetails
Onearlist.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Order.php">
<table border="2">
<tr>
<td>
<div style="padding: 40px"><label id="id">001</label> <label id="name">SMS Audio street by 50 on-ear wired</label> <label id="price">179.00$</label> Qty <input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 40px"><label id="id">002</label><label id="name">Beats Solo2 on-ear wired</label> ,<label id="price">199.00$</label> Qty<input type="text" id="qtytxt"><input type="button" value="Add to Cart" onclick="toShoppingCart()" /></div>
</td>
</tr>
<tr>
<td>
<div style="padding: 60px"></div>
</td>
</tr>
</table>
<input type="submit" value="Check Out">
</form>
<script type="text/javascript">
function toShoppingCart() {
console.log("toShoppingCart");
var id = document.getElementById("id").innerHTML;
var name = document.getElementById("name").innerHTML;
var qty = document.getElementById("qtytxt").value;
var price = parseFloat(document.getElementById("price").innerHTML);
console.log(id);
console.log(name);
console.log(qty);
console.log(price);
var request;
var itemdata = {
"id": id,
"name": name,
"qty": qty,
"price": price
};
open("Order.php", "window1");
send({
itemdetails: JSON.stringify(itemdata)
});
}
</script>
</body>
</html>
Order.php:
<?php
$data = json_decode($_GET['itemdetails']);
echo $data;
?>

To send ajax request do this:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(request.responseText); // get response form the server
}
};
request.open('GET', 'Order.php?itemdetails='+JSON.stringify(itemdata), true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.send(null);
or if you use jQuery then:
$.get('Order.php?itemdetails='+JSON.stringify(itemdata), function(response) {
});

Related

How to validate an editable column?

I'm new in Thymeleaf and try to create a contenteditable table.
So for now I have table where I put Users after adding (using controller). When I press the button "Edit" colums become editable (by using "contenteditable="true"), then I want to VALIDATE text that I'm putting over there and after successful validation save it by pressing on the button "Save" (change to "contenteditable="false"). When you see "Edit", "Save" is hidden.
I tried to create a trivial validation for Name, Phone and Email but it's not working... And also I have this on "MyFirstName" and otherss: "Argument type HTMLElement is not assignable to parameter type string" (probably there is the problem). And I don't know how to validate length of Phone Number here as well..
If you have any ideas how to make it works, please, help me, cause I'm trying very long time..
P.S. I can only use this HTML page and insert there JS-code.
Thank you!!
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Users</title>
</head>
<body>
...
<table id="myTable">
<tr th:each ="user : ${users}">
<td th:text="${user.id}" ></td> <input type="text" id="message"/>
<td th:text="${user.firstName}" id="firstName" contenteditable="false" ></td>
<td th:text="${user.lastName}" id="lastName" contenteditable="false" ></td>
<td th:text="${user.phoneNumber}" id="phoneNumber" contenteditable="false" ></td>
<td th:text="${user.email}" id="email" contenteditable="false" ></td>
<td>
<button type="button" id="edit_button" onclick="Edit()">Edit</button>
<button type="button" id="save_button" style="display: none" onclick="Save()">Save</button>
</td>
<script type="text/javascript">
$("#edit_button").click(function () {
$("#edit_button").hide();
$("#save_button").show();
});
</script>
<script type="text/javascript">
function Edit() {
let editable = document.querySelectorAll("[contenteditable=false]")
editable[0].setAttribute("contenteditable", true);
editable[1].setAttribute("contenteditable", true);
editable[2].setAttribute("contenteditable", true);
editable[3].setAttribute("contenteditable", true);
}
function Save() {
let editable = document.querySelectorAll("[contenteditable=true]");
let myFirstName = document.getElementById("firstName");
let myLastName = document.getElementById("LastName");
let myPhoneNumber = document.getElementById("phoneNumber");
let myEmail = document.getElementById("email");
let re1 = /^[a-zA-Z]+$/;
let valid1 = re1.test(myFirstName);
let re2 = /^[a-zA-Z]+$/;
let valid2 = re2.test(mySurName);
let re3 = /^\d[\d\(\)\ -]{4,14}\d$/;
let valid3 = re3.test(myPhone);
let re4 = /^[\w-\.]+#[\w-]+\.[a-z]{2,4}$/;
let valid4 = re4.test(myEmail);
if (valid1 && valid2 && valid3 && valid4){
$("#save_button").hide();
$("#edit_button").show();
editable[0].setAttribute("contenteditable", false);
editable[1].setAttribute("contenteditable", false);
editable[2].setAttribute("contenteditable", false);
editable[3].setAttribute("contenteditable", false);
} else {
alert('Type correct information!');
}
}
</script>
</tr>
</table>
</body>
</html>

Delete records from a table (Firebase)

I do not know how to delete the specific record when I click the img on the right
I want it to work like that:
Also I put an img for delete the specific record but I do not know how to add an event listener on img in the JS to delete the row and the record. Also, when I insert data in the DB I add the UID of the specific object for the delete purposes.
HTML code
<html>
<head>
<title>Fall-App Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK rel="stylesheet" href="style.css" type="text/css" media="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
</head>
<body>
<div class="cabecera">
</div>
<div class="cuerpo">
<div class="botones">
<table style="background-color:grey;height:100%; width:99%" border="10" id="logout">
<tr><td>Επεξεργασία Κοινωνικών Υπηρεσιών</td></tr>
<tr><td>Αποσύνδεση</td></tr>
</table>
</div>
<div class="welcome">
<div class="container">
<!--<form>
<input class="input" type="text" id="searchTxt" placeholder="Αναζήτηση για ...">
<input class="submit" type="submit" id="searchBtn" value="Εύρεση">
</form>-->
<input type="text" placeholder="Επιβεβαίωση Κωδικού" name="rePsw" id="rePswReg" required>
<button type="submit" id="searchBtn">Εγγραφή</button>
<table class="searchTable" style="width:100%">
<thead>
<tr>
<td>Name Of Service</td>
<td>Address</td>
<td>Postal</td>
<td>City</td>
<td>Phone</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
<form id="submitForm">
Name Of Service:<br>
<input type="text" name="name" id="nameDB"><br>
Address:<br>
<input type="text" name="address" id="addressDB">
Postal:<br>
<input type="text" name="postal" id="postalDB">
City:<br>
<input type="text" name="city" id="cityDB">
Phone:<br>
<input type="text" name="phone" id="phoneDB">
<button type="submit" id="btnInsert">Inster</button>
</form>
<script src="registered.js"></script>
</div>
</div>
<div class="pie">
</div>
</body>
</html>
JS code
(function() {
//initialize Firebase
var config = {
};
firebase.initializeApp(config);
const searchBtn = document.getElementById('searchBtn');
//const searchTxt = document.getElementById('searchTxt');
var messagesRef2 = firebase.database().ref().child('socialServices');
var counter=-1;
//bring all to the table
var messagesRef2 = firebase.database().ref().child('socialServices');
messagesRef2.on("child_added", snap => {
counter++;
var name=snap.child("name").val();
var address=snap.child("address").val();
var postal=snap.child("postal").val();
var city=snap.child("city").val();
var phone=snap.child("phone").val();
$("#tableBody").append("<tr><td>" + name + "</td><td>" + address + "</td><td>" +
postal + "</td><td>" + city + "</td><td>" + phone + "</td><td>" + "<img src='http://icons.iconarchive.com/icons/hopstarter/button/16/Button-Close-icon.png' id='Img'>" + "</td></tr>");
});
//regerence messages collection
var messagesRef = firebase.database().ref('socialServices');
//listen for form submit
document.getElementById('submitForm').addEventListener('submit', submitForm);
//submit form
function submitForm(e){
e.preventDefault();
//get values
var name=getInputVal('nameDB');
var address=getInputVal('addressDB');
var postal=getInputVal('postalDB');
var city=getInputVal('cityDB');
var phone=getInputVal('phoneDB');
//save message
saveMessage(name, address, postal, city, phone);
}
//function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//save message to firebase
function saveMessage(name, address, postal, city, phone){
var newMessageRef = messagesRef.push();
newMessageRef.set({
id: newMessageRef.key,
name: name,
address: address,
postal: postal,
city: city,
phone: phone
});
}
}());

How to find the area of the triangle using basic codes such like:

Hi guys im a grade 10 student and was asked to create a basic like calculator to solve for the area of the triangle, but i really dont know how.I can do it with the use of a radio button but my teacher said to do it without the radio input. My codes works fine but if i press clear and input a value to the base and height, it will say syntax error...please can you help me? also whenever i dont put a value on base and height,it says 0 instead of syntax error,so please help me....(also sorry about earlier, im just new to this site)
this is my code:
<html>
<head>
<title>hfsabfhsabfihs</title>
</head>
<body>
<script type="text/javascript">
<!--
function checkbutton() {
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
if (document.form1.checked == false) {
alert("Syntax Error")
} else {
alert(num1 * num2 / 2);
}
}
function clearbutton() {
document.form1.checked = false;
var num1 = document.getElementById("input1").value = "";
var num2 = document.getElementById("input2").value = "";
}
//-->
</script>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" value="Compute" onclick="checkbutton()">
<input type="button" value="Clear" onclick="clearbutton()">
</body>
</html>
problem is on clear function function
function clearbutton()
{
// document.form1.checked= false;
var num1 = document.getElementById("input1").value="";
var num2 = document.getElementById("input2").value="";
}
you are getting this error because you have set a variable here i.e form1.checked. either remove this variable or change its value on calculation function
Hope the below code helps:
// vairbale
const baseInput = document.querySelector("#input1")
const heightInput = document.querySelector("#input2")
const coputeBTn = document.querySelector("#Compute")
const areaTriangle = (base, height) =>{
let total =""
let error = false
let errorMessage = ""
if(base != "" && height != ""){
error = false
total = base * height / 2
}else{
error = true
errorMessage = "Please fill all inputs."
return errorMessage
}
return total
}
// Calling Function
coputeBTn.addEventListener("click", ()=>{
console.log(areaTriangle(Number(baseInput.value), Number(heightInput.value)))
})
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" id="Compute" value="Compute">
<input type="button" value="Clear" onclick="clearbutton()">
</form>
</body>
</html>

passing value from modal to main form

I have a contact script as follows:
<?php
Session_start();
if (!isset($_SESSION['username'])){
header("Location:../index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Modal</title>
<link rel="stylesheet" href="../css/style.css">
<link href="../libraries/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="../libraries/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="../libraries/css/jquery-ui.css">
<script src="../libraries/js/jquery-1.10.2.js"></script>
<script src="../libraries/js/jquery-ui.js"></script>
<script type="text/javascript" src="../libraries/date/jquery/jquery-1.8.3.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="../libraries/date/bootstrap/js/bootstrap.min.js"></script>
<script>
// Get Organization ID
function getOrganizationID(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getorganizationid.php?q="+str,true);
xmlhttp.send();
}
}
// Auto Complete for Organization field
$(function() {
$( "#skills" ).autocomplete({
source: '../libraries/organization/search.php'
});
});
</script>
</head>
<script type="text/javascript">
//
function chName(value) {
var val_fname = document.getElementById('fname').value;
var val_lname = document.getElementById('lname').value;
var val_fullname = val_fname + ' ' + val_lname;
document.getElementById('org').value = val_fullname;
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<div id="main">
<form name="create" id="create" method="post" action="do_create.php">
<table style="width:100%;font-weight:bold;">
<tr>
<td>First Name</td>
<td><input id="fname" name="fname" type="text" required>*</td>
<td>Last Name</td>
<td><input id="lname" name="lname" type="text" onblur="chName(this.value)" required>*</td>
</tr>
<tr>
<td>Phone</td>
<td><input name="phone" type="text" required>*</td>
<td>Email</td>
<td><input name="email" type="text" required>*</td>
</tr>
<tr>
<td>Mobile Phone</td>
<td><input name="mobile" type="text"></td>
<td>Organization</td>
<td>
<input id="skills" type="text" name="skills" value="" onblur="getOrganizationID(this.value);return false;">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">+</button>
<div id="txtHint" style="width:1px;height:1px;">
<input id="organization_id" name="organization" type="hidden" readonly>
</div>
<input id="org1" type="hidden" name="ocname" value="<?php echo $hash;?>">
</td>
</tr>
</table>
</form>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<script type="text/javascript">
function chOrg(value) {
var val_oname = document.getElementById('oname').value;
document.getElementById('skills').value = val_oname;
}
</script>
<form name="addorganization" id="addorganization" method="post" action="add_organization.php" target="myIframe" onsubmit="chOrg(this.value)">
<div id="headsum">
<strong>Create Organization</strong>
<input style="float:right;" name="add_organization" type="submit" value="SAVE">
</div>
<table style="width:100%;font-weight:bold;text-align:left;">
<tr>
<td>Organization Name</td>
<td><input name="oname" type="text" required>*</td>
<td>Contact Name</td>
<td><input id="org" type="text" name="org" value="" readonly>*
<input id="org1" type="hidden" name="ocname" value="<?php echo $hash;?>"></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="ophone" type="text" required>*</td>
<td>Email</td>
<td><input name="oemail" type="text" required>*</td>
</tr>
</table>
</form>
<iframe style="display:none;" src="" name="myIframe" id="myIframe">
</iframe>
</div>
</div>
when I click the button beside the organization filed, will appear a popup (modal) to add an organization.
organization contact name on the form is automatically populated with the name that fill in the main form.
What I want to ask here is:
how after the organization form stored, the name of the organization and hash on the main form will automatically be filled with the names and hashes saved from earlier organizational form, because of what I have tried has not succeeded
Hello Take one hidden field in main form. so after submitting the form pass that value to the hidden field.
Hope it helps !!

Delete array graphically in Javascript

I'm having trouble figuring out how to do this, and well, need help.
I'm trying to put my information into an array that's going to be shown and always be able to grow. I need help deleting specific entries into it, either by searching for one or by pointing a mouse and deleting it,
Is there any nice easy way to do it?
<!doctype html>
<html lang="sv">
<body>
<head>
<meta charset="UTF-8">
</title>
</head>
<body>
<input type="text" placeholder="Förnamn" id="name" autofocus>
<input type="date" id="pnummer" autofocus>
<input type="text" placeholder="Efternamn" id="enamn" autofocus>
<input type="button" value="mata in" onclick="register()">
<input type="button" value="visa" onclick="show()">
<script type="text/javascript">
array=[]
function register()
{
var fnamn = document.getElementById("name").value;
var enamn = document.getElementById("enamn").value;
var pnummer = document.getElementById("pnummer").value;
var p1 = new Person(fnamn,pnummer,enamn);
array.push(p1);
}
function Person(fnamn, pnummer, enamn)
{
this.fnamn=fnamn;
this.pnummer=pnummer;
this.enamn=enamn;
this.visa=function()
{
var panel ="Förnamn:"+" "+this.fnamn+" "+"Efternamn:"+" "+this.enamn+" "+"Personnummer:"+" "+this.pnummer+"<br>";
return panel;
}
}
function show(){
var showperson=document.getElementById("new");
showperson.innerHTML="";
var i=0;
while (array.length>i)
{
showperson.innerHTML+=array[i].visa()
i++;
}
}
</script>
<p id="new"></p>
<div id="panel"></div>
</body>
</html>
I am not 100% sure what you're trying to do or what some of those words mean but is this what you're trying to do?
var peopleTracker = {};
var peopleCounter = 0;
function addPerson()
{
// get the values
var firstName = document.getElementById("firstName").value.trim();
var lastName = document.getElementById("lastName").value.trim();
var birthday = document.getElementById("birthday").value.trim();
// make sure none are blank
if(firstName == "" || lastName == "" || birthday == "") return;
// give each person an ID so we can remove them later
var personID = ++peopleCounter;
peopleTracker[personID] = {
"firstName" : firstName,
"lastName" : lastName,
"birthday" : birthday
};
// add the person to the table
var row = document.getElementById("peopleList").insertRow();
row.insertCell().innerText = firstName;
row.insertCell().innerText = lastName;
row.insertCell().innerText = birthday;
row.insertCell().innerHTML = 'remove';
}
// delete a user from the tracker and remove the row
function removePerson(row, personID)
{
delete peopleTracker[personID];
row.parentNode.removeChild(row);
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>the dingo ate my baby</title>
</head>
<body>
<input type="text" placeholder="First Name" id="firstName" autofocus>
<input type="text" placeholder="Sur Name" id="lastName" autofocus>
<input type="date" id="birthday" autofocus>
<input type="button" value="Add Person" onclick="addPerson()">
<br /><br />
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Sur Name</th>
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tbody id="peopleList"></tbody>
</table>
</body>
</html>
A few thoughts:
If you're going to use an array to delete then you're going to need to use some unique ID to be able to find the person you want to delete. You cannot use the array index because that will change as you remove people from the array.
By using an object to store the users you can delete by using a unique ID that changes for each user added.
I jQuery is an option, you could find the index of your clicked <div> and delete the element with something like the following function:
$( "div.someIdYouGiveIt" ).click(function() {
var index = $( "div.someClassYouGiveIt" ).index( this );
array.splice(index, 1);
});

Categories