How to I save a list group in SQL database? - javascript

I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.
<h4>Subjects</h4>
<ul class="list-group list" id='subjectlist' name='subjectlist' >
</ul>
<div class="form-group">
<input class="submit" name="submit" type="submit" value="Save">
</div>
</form>
<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>
<script>
function getsubject(){
var ul = document.getElementById("subjectlist");
var candidate = document.getElementById("st");
var SelectedValue = candidate.options[candidate.selectedIndex].text;
var li = document.createElement("li");
li.setAttribute('class',"list-group-item");
li.setAttribute('id',"subjectlistitem");
li.appendChild(document.createTextNode(SelectedValue));
ul.appendChild(li);
}
</script>
<?php
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$sectioncode = $_POST['sc'];
$sectiongroup = $_POST['ccg'];
$selectedsubject = $_POST['st'];
$subjectlist = $_POST['subjectlist'];
$i = 0;
foreach ($subjectlist as $qst) {
$sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
'" . $subjectlist[$i] . "')";
if ($link->query($sql) === TRUE) {
echo "success";
} else {echo "error" . $link->error;}
$i++;}
}
?>

because $_POST,$_GET only deal with <input> tags and <ul>,<li> are not input methods.

Related

Genereting 'n' html inputs based on database variable

My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```
Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.

Variable select elements with options pulled from database

Been kinda stuck with this one for awhile.
I need my code to create 2 elements on a click of a button (Text input and Select). The Select element needs to be populated with values from a database.
So far I've got this:
<!DOCTYPE html>
<html>
<head>
var counter = 1;
var dynamicInput=[];
function removeInput(){
var elem = document.getElementById('ingredients');
elem.removeChild(elem.lastChild);
/*return elem.parentNode.removeChild(elem);*/
counter--;
}
function addInput(){
var newdiv = document.createElement('div');
newdiv.id = dynamicInput[counter];
newdiv.innerHTML = "Entry " + (counter) + " <br><input type='text' name='quantities[]'><select name='products[]'></select>";
counter++;
document.getElementById('ingredients').appendChild(newdiv);
}
</script>
<?php
$link = mysqli_connect("localhost", "root", "", "cocktails");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
</head>
<body>
<form method="POST">
Ingredients:<br>
<div id="ingredients">
<div id="dynamicInput[0]">
<input type="text" name="quantities[]">
<select name="products[]">
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>
<button type="button" onClick="addInput();">+</button>
<button type="button" onClick="removeInput();">-</button>
</div>
</div>
</form>
</body>
</html>
How can I populate the select that's created on a click of the button?
Of course whatever the user selects I will need to work with. How can I work with those values after?
Any pointers in the right direction will be greatly appreciated.

How to pass multiple workplace names with same names/ids from form via AJAX to another php page so I can update my MySQL table.

I found solutions for similar questions from stackoverflow as below, but they didn't work for me.
Possible Solution 1 here
Possible Solution 2 here
For just one workplace input field, this code works perfectly fine, but by using jQuery functions, I am prepending multiple workplace field dynamically.
Also, I don't have any trouble updating data in my MySQL database as far as I am using only one input field for workplace.
But when I prepend multiple input fields for workplace, I have trouble passing my different workplace name to php script.
So far, I have tried using solutions such as I used class="workplace" instead of id="workplace", but with that I don't even get values of my input field even on the same page when I used "alert(companyname);" to see if I get to see submitted values in alert. But no!
Also, I tried making my and other ways such as name="workplace['+index+'][name]", etc. None worked.
Database name: workplacedb
table name: companyname
fields: c_id ,user_id, workplace.
$(function() {
var count = 0;
/* WORKPLACE codes start here */
$('.add-workplace').click(function() {
var index = $('.workplace-input').length + 1;
//$('.add-workplace').hide();
$(".collapse").collapse('show');
$('.workplace-lines').prepend('' +
'<div class="input-group workplace-input">' +
'<input type="text" name="workplacename" id="workplace" class="form-control"/>' +
'<span class="input-group-btn">' +
'<button class="btn btn-danger btn-remove-workplace" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
'</span>' +
'</div>'
);
});
$(document.body).on('click', '.btn-remove-workplace', function() {
$(this).closest('.workplace-input').remove();
});
$('.add-workplace').one('click', function() {
count = 1;
});
$('.add-workplace').click(function() {
if (count > 0) {
$('.workplace-lines').append('<span class="input-group-btn main-btn">' + '<button class="btn btn-success btn-workplacesubmit" type="submit" name="submitWeb"><span class="glyphicon glyphicon-check">Submit</span></button>' + '<button class="btn btn-danger btn-workplacecancel" type="button" name="cancel" style="margin-left:15px"><span class="glyphicon glyphicon-remove">Cancel</span></button>' + '</span>');
count = 0;
}
});
// Cancel button click for workplace fields
$(document).on('click', '.btn-workplacecancel', function() {
$('.workplace-input').remove();
$('.main-btn').remove();
count = 1;
});
var workplace_form = $('#workplaceinfo');
workplace_form.submit(function(event) {
var companyname = $('#workplace').val();
alert(companyname);
if ($.trim(companyname) != '') {
$.post('about.php', $("#workplaceinfo").serialize(), function(data) {
$('.workplace-lines').hide();
$('.main-btn').hide();
$('#results').html(data);
//alert(data);
});
}
// Prevent default form action
event.preventDefault();
});
});
<!-- about.php here --> <?php require_once("home_userinfo_retrieve.php");
$mysqli=new mysqli('localhost',
'root',
'',
'databasename');
$sql="UPDATE tablename SET workplace=? WHERE user_id='$userid_logged_in'";
$stmt=$ mysqli->prepare($sql);
$stmt->bind_param("s",
$_POST['workplacename']);
$stmt->execute();
$stmt=$mysqli->prepare("SELECT * FROM detailed_user_info WHERE user_id = ?");
$stmt->bind_param("s",
$userid_logged_in);
$stmt->execute();
$result=$stmt->get_result();
while($row=$result->fetch_object()) {
$rows[]=$row;
}
?> <ul> <?php foreach ($rows as $row):?> <li> <?php echo $row->workplace;
?></li> <?php endforeach;
?> </ul>
<form action="about.php" method="post" name="workplaceinfo" id="workplaceinfo">
<div class="form-group workplace">
<div class="workplace-lines">
<h5 class="add-workplace"> <a><span class="glyphicon glyphicon-plus"></span> Add your workplace </a> </h5>
</div>
<h5 id="results">
</h5>
</div>
</form>

how to add new select box after clicking a button in jquery

i dont know if its possible using jquery,..i have a select option that has an array of data came from database and what i want is that whenever i click a button, another select option will popout like the first select option..
here is the code of my select option
<select class="form-control" name="room[]" id="room[]">
<option value="" default>Select</option>
<?php
$room = $subjectsClass->room();
foreach ($room as $key => $value) {
echo '<option value=" ' . $value['room_id'] .' ">' . $value['room_no'] . '</option>';
}
?>
</select>
<button type="button" class="btn btn-default" id="addRooms" >Add more Rooms?</button>
<script>
$('#addRooms').click(function(){
//append another select box with data from database,..how??
});
</script>
Let's say you have that wrapped into a div like:
<div id="the_div_of_wrapping"> all your stuff </div>
Then I would do:
var the_select = $("#room[]");
var the_id = the_select.prop("id");
var the_number_of_selects = $("select").length;
var the_div_of_wrapping = $("#the_div_of_wrapping");
the_select.clone().prop("id", the_id + the_number_of_selects);
the_div_of_wrapping.append(the_select);
.
Update:
As discussed in the comments, I would remove id since it is unnecessary and then the code would be:
var the_select = $("#room[]");
var the_div_of_wrapping = $("#the_div_of_wrapping");
the_select.clone();
the_div_of_wrapping.append(the_select);

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

Categories