Process user data in PHP from JavaScript in HTML with multiple selections - javascript

just a fair warning: I'm a HTML, PHP and JavaScript noob.
I wrote code to get multiple selection boxes, where the selectable content from the second box is dependent on the
selection of the first box.
So like:
Brands: if Asus is selected the next box: and the last box is prime is selected:
Asus Prime B560
MSI Plus Z590 etc.
This has to be expendable to newer models, brands etc.
The Code I have so far:
(hersteller means manufacturer)
index.html
<!DOCTYPE html>
<head></head>
<body>
<form name="form1" id="form1" action="redir.php">
Hersteller: <select name="hersteller" id="hersteller">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Modell: <select name="model" id="model">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Chipset: <select name="chipid" id="chipid">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
<input type="submit" value="weiter">
<script>var subjectObject = {
"Asus": {
"Prime": ["B560", "Z490", "Z590", "Z690"],
"ProArt": ["Z490"],
"ROG": ["Z690 ITX"]
},
"MSI": {
"Torpedo": ["Z490", "Z590", "Z690"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("hersteller");
var topicSel = document.getElementById("model");
var chapterSel = document.getElementById("chipid");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
chapterSel.length = 1;
topicSel.length = 1;
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() {
chapterSel.length = 1;
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}</script>
</form>
</body>
redir.php
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
if ($hersteller = "Asus") {
if($model = "Prime"){
if($chipid = "B560"){
header("Location: /driver_sites/Asus_Prime_B560.html");
}
}
exit();
}
//elseif ($items = 'Item2') {
//header("Location: item2.php");
//}
?>
I want to process the data selected and redirect to a specific site. For example
if the user selects "Asus" -> "Prime" -> "B560" and clicks on "weiter" (submit), it should redirect him to
a page like Asus_Prime_B560.html
How can this be done?
Thanks in advance :)
I tried multiple ways in PHP but nothing seems to work and my knowlege is limited.
Also, I searched what feels like the entire internet but to no avail.

I hope I understood your problem, what about changing your "redir.php" file as follows:
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
header("Location: /driver_sites/".$page);
What this does is build the "page filename" based on the inputs and just redirect to it. Let's say that the user selected following values:
$hersteller = 'Asus';
$model = 'Prime';
$chipid = 'B560';
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
$page is now => Asus_Prime_B560.html
This example implies that all pages have the same format HERSTELLER_MODEL_CHIPID.html
Edit:
Based on your comment I will add some info
When you see some URL containing ?some=thing&foo=bar the part after the ? (question mark) is called query string. This query string parameters can be accessed by PHP using the $_GET superglobal (i.e. to read param foo i can do
$foo = $_GET['foo']; //$foo now contains "bar"
On the other end, if the form has been submitted using the POST method (<form method="post" ....>) the the data can be accessed using the $_POST superglobal
$something = $_POST['paramNam'];

Related

Javascript generated select not posting in PHP

I have searched far and wide and have not seen an answer for this. Forgive me if one exists.
I have a PHP page, in which user can generate new html select fields by pressing a button. I use Javascript to generate the new select fields. The user can then select one option from the generated select field. I need the value the user chose in PHP code below the form, to submit the form values to database.
My problem is that PHP doesn't seem to recognize the new generated select fields, which is why it won't post.
var_dump($_POST) doesn't show the new select field. I have also tried to name the new select as name="choice1[]", but that also has not posted. Choice1 is always undefined.
All of my code is on the same PHP page, apart from sql query to populate the select options.
This is what Javascript generates inside a form:
<select class="form-control" id="choose1" name="choice1">
<option value="1:x">Text</option>
<option value="2:y">Text</option>
<option value="3:z">Text</option>
</select>
This is where I try to get the value, after submit button is pressed:
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr1[0];
$tName = $arr1[1];
}
The Javascript works fine, the values are shown on the page fine. The only part not working is the post method (well, only for this specific select field. Other's work fine, as those are hard coded to html). Submit button works fine, everything else gets submitted.
My question is if there is a way for me to get the post values in PHP without reloading the page?
Or if reload is needed, how to do this without closing the form modal?
Or even more of a general question would be.. How do I do this?
EDIT:
Here is my form code. I deleted bunch of other stuff from it just to show the parts I have the problem with. If the divs are weird, it's because of that.
<form class="form-horizontal" method="post" action="">
<div class="modal-header">
<h4 class="modal-title">Change</h4>
</div>
<div class='modal-body'>
<div class='row'>
<label class="col-sm-3"> Product: </label>
<div class="col-sm-8" id="selectProd">
<!-- **This is where new select is generated** -->
<select class='form-control' id='valinta' name='choice'>
<?php
$sql0= "SELECT tuotenro, tuotenimi FROM vaateHenkilot WHERE asnro = '". $_GET['b']."' AND henknro = '". $_GET['a']."' GROUP BY tuotenro, tuotenimi";
$req = sqlsrv_query($con, $sql0) or die(print_r(sqlsrv_errors(),true));
$t = '';
while($row = sqlsrv_fetch_array($req)) {
$t = array(
array (
'nro' => $row['tuotenro'],
'nimi' => $row['tuotenimi'],
)
);
$tuotteetIN = array_column($t, 'nimi', 'nro');
foreach($tuotteetIN as $key => $value) {
?>
<option value="<?php echo $key ?>:<?php echo $value ?>"><?php echo $value ?></option>
<?php
}
}
?>
</select>
<br>
</div>
<div class="col-sm-1">
<button type='button' class='btn' onclick='addSelectBox()'>+</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="saveButton">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
<?php
if (isset($_POST['saveButton'])) {
$choice = $_POST["choice"];
$parts = $choice;
$arr = explode(':', $parts);
$tNum = $arr[0];
$tName = $arr[1];
if (isset($_POST['choice1'])){
$choice1 = $_POST['choice1'];
$parts1 = $choice1;
$arr1 = explode(':', $parts1);
$tNum = $arr[0] . ', ' . $arr1[0];
$tName = $arr[1] . ', ' . $arr1[1];
}
*Here is the sql query*
}
?>
I have another select there, which has the same values. That one works well.
I'll add the Javascript here that creates the new select, as well.
<script type="text/javascript">
var j = 0;
function addSelectBox (){
if (j < 3){
var parentDiv = document.getElementById ("selectProd");
var selectElement = document.createElement ("select");
j++;
selectElement.setAttribute("class", "form-control");
selectElement.setAttribute("id", "choose" + j);
selectElement.setAttribute("name", "choice" + j);
var tuotteet = '';
$.ajax({
type: 'GET',
url: 'productHelp.php?asi=<?php echo $asnro; ?>&hen=<?php echo $henro; ?>',
data: tuotteet,
datatype: 'json',
cache: false,
success: function (data) {
var tnimi = data.split(";");
for (var i=0;i < tnimi.length -1;i++){
var tnro = tnimi[i].split(",");
var option = new Option (tnro[1], tnro[0]+":"+tnro[1]);
selectElement.options[selectElement.options.length] = option;
}
}
});
parentDiv.appendChild (selectElement);
parentDiv.appendChild(linebreak);
}
}
</script>
Turns out the problem was as "stupid" and simple as I figured it had to be.
Taking the modals with the functionality out from the table structure made it work fine.
Good to learn something new about formatting everyday!

Best way to append querystring to url when a checkbox is selected while saving checkbox state?

I am making a checklist form and currently i am able to append the value of the selected boxes to the url in I feel an inefficient way and the main issue is that the state of the checkbox doesnt save either so a user cant see what they checked or uncheck.
This is the html code
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()">
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()">
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()">
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()">
</form>
This is the script to make the url
let form = document.getElementById("carForm")
let checkboxes = document.getElementsByTagName("input")
var vals = "";
let formSubmit = () => {
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals = checkboxes[i].value
// append checkbox values to url
var url = window.location.href;
if (url.indexOf('?') > -1){
// if a paramter already exists, append using
url += `&make=${vals}`
}else{
url += `?make=${vals}`
}
window.location.href = url;
}
console.log(vals);
}
}
function checkboxChanged() {
formSubmit()
}
</script>
So for instance if kia and honda were selected the url would be
/inventory?make=kia&make=honda
So if this is inefficient whats a better way of doing this and how do i ensure the checkbox state is persisted after the page is reloaded I am using nodejs/expressjs on server side and ejs
var makes=[];
...
for (var i=0;i<checkboxes.length;i++) {
if (checkboxes[i].checked) makes.push(checkboxes[i].value);
}
...
url+='&makes='+makes.join(',');
This will give you a comma delimited list; you can string split it on the server side.
You should take a look at URLSearchParams. Using it, you could do something like this:
const searchParams = new URLSearchParams(location.search);
document.querySelector('input[type=checkbox]').forEach(cb => {
if (cb.checked) {
searchParams.append('make', cb.value)
}
});
location.href = location.href.replace(location.search, '?' + searchParams.toString())
I think that you should not define all the parametres of the url as make=..., but with ${vals}=checked. Then you can read it easily with php and just check the names that are defined, but you will have to define a name for your chackboxes.
Sorry for my approximative english, I am swiss and speak french.
If you have access to a server-side language, like PHP, use that to check the URL and auto-check the boxes when the page loads. Something along these lines:
<?php
$bools = [
"kia" => isset($_GET['kia']),
"bmw" => isset($_GET['bmw']),
"mercedes" => isset($_GET['mercedes']),
"toyota" => isset($_GET['toyota'])
];
?>
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()" <?= $bools['bmw'] ? 'checked' : '' ?>>
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()" <?= $bools['mercedes'] ? 'checked' : '' ?>>
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()" <?= $bools['honda'] ? 'checked' : '' ?>>
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()" <?= $bools['toyota'] ? 'checked' : '' ?>>
</form>
Protip: In PHP, you can use value="car[]" in order to submit an array of values which will already be an array type in PHP!
If you don't have access to server-side, or you don't wish to use it, then check the URL on page-load:
window.onload = () => {
for (const el of checkboxes) {
// Check the URL's params:
// From link below
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get(el.value);
if (myParam != null) {
el.checked = true;
}
}
}
(Get URL params reference, there are more options with better support than what I used. I just used the simplest option)

How to pass same class/id name php values from radio button to javascript?

This is my problem. I am looping items from the database that contains items name and id. I have a radio button for each items. The id of that item is stored in the radio buttons value....Now what i want to achieve is when i click on the submit button,it will call a function call save() in javascript and save all the selected items ONLY .... i've been trying this for hours but i cant get it worked.
Here are my codes....
When i do my while looping from the DB, it will display the radio button and the items name...
<?php
$retrieveQuery = "SELECT * FROM `itemdb` WHERE `approve`= 1 AND `userId` = '$userId';";
$retrieveresult = mysqli_query($dbconnect, $retrieveQuery);
if(mysqli_num_rows($retrieveresult) > 0)
{
while($retrieverow = mysqli_fetch_assoc($retrieveresult))
{
?>
<p> </p>
<div style="background-color: rgba(0, 0, 0, 0.16);">
<input style="margin-bottom: -19px;" type="checkbox" class="item" name="item[]" value=<?php echo $retrieverow['itemID'] ?>>
<p style="margin-left: 26px;"><?php echo $retrieverow['itemName'] ?></p>
<p style="margin-top:-10px;margin-left:28px"><i><?php echo $retrieverow['category'] ?></i></p>
</div>
<?php
}
}
else
{
echo "Test : There is no approve Items to be displayed";
echo "Either wait for the admin to approve or upload items to start Trading ! ";
}
?>
This is my script:(How can i save my items?)
function save()
{
var f = document.getElementsByClassName('item').value; //my own items chosen frm invntry
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("confirmTrade").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","trade.php?f="+f,true);
xmlhttp.send();
}
Right after i click the save() function it will send the data to another page using ajax method....
PS: Everything works fine...Other variables are passed successfully but only one item variable is being passed....
Thanks in advance!
Without looking into it too much, take a look at this line:
var f = document.getElementsByClassName('item').value;
document.getElementsByClassName gets an HTMLCollection of elements, so calling value on this doesn't make much sense. You'll need to loop through them and find the selected ones. I have it building an array then joining it into a comma separated list:
var checkboxes = document.getElementsByClassName('item');
var f = [];
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked == true)
f.push(checkboxes[i].value);
}
f = f.join();//makes comma seperated list
//proceed with ajax call

Drop Down Menu Validation JS

I have a dynamically generated drop down menus using PHP, I use these manes on different web pages, Now I also want to add some JS validation to these menus so that the user does not forget to choose an option while filling in a form.
The problem is that my JS code does not work and does not validate my menus, The code looks good to me I have IF statements where they check if the first option value =0 therefore there has not been selection but it still does not work
PHP code:
$option='<select id="Forex" name="workshop">';
$option.='<option value="0">Select Forex Workshop</option>';
$option.='';
while($result = mysqli_fetch_assoc($query))
{
if($timestamp < $result['endingDate'])
{
$option.='<option id="'.$result['id'].'" value='.$result['endingDate'].'>'.$result['course']." ".$result['schedule'].'</option>';
}
}
$option.='</select>';
return $option;
}
function getBinary($link){
$timestamp = date("Y-m-d");
$query2 = mysqli_query($link, $sql2);
$option2='<select id="Binary" name="workshop">';
$option2.='<option value="0">Select Binary Workshop</option>';
$option2.='';
while($result2 = mysqli_fetch_assoc($query2))
{
if($timestamp < $result2['endingDate'])
{
$option2.='<option id="'.$result2['id'].'" value="'.$result2['endingDate'].'">'.$result2['course']." ".$result2['schedule'].'</option>';
}
}
$option2.='</select>';
return $option2;
}
?>
JS CODE:
var workshop=document.getElementById('Binary').value;
if(workshop==0){
document.getElementById('Binary').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop1";
return false;
}else{
document.getElementById('Binary').style.borderColor = "green";
}
var workshop2=document.getElementById('Forex').value;
if(workshop2==0){
document.getElementById('Forex').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop";
return false;
}else{
document.getElementById('Forex').style.borderColor = "green";
}
You have wrongly named the select id/name.
$option='<select id="Forex" name="workshop">';
and yet you are trying to access it from JS by calling it by id workshop while the name attribute is workshop not the id.
var work=document.getElementById('workshop').value;
The id is Forex not workshop. And you call Forex from different Js line. I think your error is in trying to access a null variable. Unless you have another element with the id workshop that I'm not aware of.

How to get variables to pass to javascript math.random

So I am just totally clueless how to make this happen. Hoping someone could provide some guidance. I have built a chat system that allows random rolls of dice (for a D&D game). Within the chat div I have a form that allows to select the quantity of dice, as well as the dice type (ie. 4 sides, 6 sided, 10 sided, etc.). It then passes the form input with php into a chat.txt file. I am using ajax to display the chat.txt in the chat div.
So when I originally started I made it function for 1d20 (1 20 sided dice). And used x.value=Math.floor((Math.random()*20)+1) to make it pick a random number between 1 and 20. Well now I need it to be able to detect the quantity of dice, as well as the amount of sides of the dice(d4, d6, d8). Is there a way to pass the quantity and dice variables into the math.random ? and even better yet, then display each number separately (meaning say you roll 2 d6 and get a 5 and a 3. I would like to have it display the 5 and 3 separately. But that is not totally needed, mostly i need to know how to get different random ranges based on the $quantity and $dice. Or maybe a totally different approach that would work? Any and all help is much appreciated.
<div id="pageWrap">
<div id="expander"> Expand</div>
<?php
if(isset($_POST['submit']))//on submit
{
$roll = $_POST['roll'];
$quantity= $_POST['quantity'];
$dice = $_POST['dice'];
$nickname = htmlentities(strip_tags($_POST['nickname']));
$file = fopen('chat.txt', 'a');
fwrite($file, "<span>". $nickname . " :</span>" . $roll = str_replace("\n", " ", " <em> Rolls </em>$quantity $dice <em>for</em> $roll") . "\n");
fclose($file);
}
?>
<form action="" id="rollBox" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<input type="number" name="quantity" min="1" max="10">
<select name="dice">
<option value="d4">d4</option>
<option value="d6">d6</option>
<option value="d8">d8</option>
<option value="d10">d10</option>
<option value="d12">d12</option>
<option value="d20">d20</option>
</select>
<button type="submit" name="submit" >Roll</button>
</form>
<script>
$(document).ready(function () {
$('#rollBox').submit(function(e) {
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
e.preventDefault();
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {}
});
return false;
});
});
</script>
</form>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '200' ></textarea>
</form>
</div>
This function takes number of dices and dice type and will return an array filled with random number. However, what you need is loop, javascirpt loop to loop thru the number of dices and get a random value for each dice.
function getRandome (num_dice , dice_type) {
var result=[];
for (var i = 0 ; i < num_dice; i++) {
result[i] = Math.floor((Math.random()*dice_type)+1)
}
return result;
}
It's up to you how you want to get the input values, but here's a FULL ANSWER JS FIDDLE
now let's see this example
var num_dice = 5;// number of dices
var dice_type = 3;//3 faces
var randomArray = [] ;//will store the random result here as an array
randomArray = getRandome (num_dice , type );
var randomString = randomeArray.join(",");//convert the array to string adding a comma "," between indexes;
//assign the string result of random to a text field, div, span etc
$("#demo").val(randomString);//jquery
//OR
document.getElementById("demo").value = randomString;//javascript

Categories

Resources