I'm having some issues submitting an HTML form. The form allows the user to add skills to the HTML page using a button. These newly created skills then need to be inserted into the database. The problem is, I can only insert one skill at a time. The skills are entered as checkboxes and all checked skills should be entered in the database. I think my issue is that each checkbox that is created dynamically shares the same $skill_name variable, but this is not an issue when I grab existing skills from the database to display. I added some ajax to try and save each skill in a post statement as they are created, but it doesn't help when I actually go to insert. The INSERT statement looks something like this:
if(!empty($_POST["backend"])){
$backend = $_POST["backend"];
$sql2 = "INSERT INTO skill (skill_cat_id, skill_name) VALUES (?,?)";
$skill_cat_id = 1;
for ($i = 0; $i < count($backend); $i++){
$skill_name = $_POST["skill_name"];
if($stmt = $mysqli->prepare($sql2)){
$stmt->bind_param("is", $skill_cat_id, $backend[$i]);
if ($stmt->execute()) {
echo "<script>
alert('Success!');
</script>";
}
else{
echo "<script>
alert('Failure!');
</script>";
}
}
}
}
And the HTML for looks like this:
<h5>Backend Technologies </h5>
<div class="container">
<div id = "backendDiv">
<?php
$backend=getbackendtech();
while($row = $backend -> fetch_assoc()) {
// echo "<input type='checkbox' value='{$data['skill_name']}'>". $data['skill_name'];
echo "<div class=\"list-group-item checkbox\" id = \"backendCheckBoxes\">
<label><input type=\"checkbox\" name=\"backend[]\" class=\"common_selector form\" value='{$row['skill_name']}'> {$row['skill_name']}</label>
</div>";
}
echo"<input type=\"button\" class='btn btn-warning btn-sm' id = \"addBackendButton\" value = \"Add\" onclick=\"addSkill('backendCheckBoxes', 'backendDiv', 'backend', 'addBackendButton')\">";
?>
</div>
</div>
And here is the addSkill event:
function addSkill(checkBoxDivId, divId, nameId, buttonId){
//Variables
//Creating new elements for new skills and
//setting their attributes
let count = 0;
console.log(checkBoxDivId);
let existingSkills = document.querySelectorAll("div[id =" + checkBoxDivId +"]");
console.log(existingSkills);
for (let i = 0; i < existingSkills.length; i++){
count++;
}
let uniqueId = count+1;
console.log(uniqueId);
let hiddenValue = document.createElement("input");
hiddenValue.setAttribute("hidden", true);
hiddenValue.setAttribute("name", "skill_name");
let checkBoxDiv = document.createElement("div");
checkBoxDiv.setAttribute("id", checkBoxDivId);
checkBoxDiv.setAttribute("class", "list-group-item checkbox");
//console.log(checkBoxDiv);
let textBoxParent = document.getElementById(divId);
//console.log(textBoxParent);
let newTextBox = document.createElement("input");
newTextBox.setAttribute("type","text");
newTextBox.setAttribute("id", "newTextBox");
let newCheckBox = document.createElement("input");
newCheckBox.setAttribute("name", nameId);
newCheckBox.setAttribute("class", "common_selector form");
newCheckBox.setAttribute("type","checkbox");
newCheckBox.setAttribute("checked", true);
newCheckBox.setAttribute("value", uniqueId);
let newLabel = document.createElement("label");
newLabel.setAttribute("for", "newCheckBox");
let addButton = document.getElementById(buttonId);
//console.log(addButton);
//adding textbox to page
textBoxParent.appendChild(newTextBox);
//When an enter key is pressed the newly created textBox
//will be removed and a new checkbox will appear
newTextBox.addEventListener("keypress", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
//console.log(newTextBox.value);
//Canceling the default action, if needed
event.preventDefault();
event.stopPropagation();
//Setting Label value
newLabel.innerHTML = newTextBox.value;
let skill_name = newLabel.innerHTML;
console.log(newCheckBox.getAttribute("value"));
//posting skill name to database
hiddenValue.setAttribute("value", newLabel.innerHTML);
console.log(hiddenValue);
//Remove textbox from page
textBoxParent.removeChild(newTextBox);
//Adding new Checkbox to Div
checkBoxDiv.appendChild(newCheckBox);
checkBoxDiv.appendChild(newLabel);
//checkBoxDiv.appendChild(hiddenValue);
//Adding new Checkbox Div to page
addButton.before(checkBoxDiv);
$.ajax({
type: 'post',
data: {skill_name: skill_name},
success: function(response){
alert(skill_name);
}
});
}
});
}
Related
how can i differentiate multiple rows with same class using javascript? i've searched it but it shows only jquery and i know nothing about it.
my rows always shows the amount in inventory of the last product selected like this example in this pic the example
here's what i wrote as js function:`
function showAmount(variable)
{
this.product = variable;
if(product == '')
{
document.getElementsByClassName('qte').innerHTML = " ";
}else
{
const xmlhttp = new XMLHttpRequest();
var table = document.getElementById('tbody');
//var rows = table.rows.length;
//console.log(rows);
var rows = document.getElementsByClassName('qte');
console.log(rows[1]);
xmlhttp.onload = function(){
myObj = JSON.parse(this.responseText);
for(var j = 0; j < rows.length; j++)
{
for (var i = 0; i < myObj.length; i++)
{
if(product === myObj[i]['NomArt'])
{
rows[j].innerHTML = myObj[i]['Qte'];
}
}
}
}
xmlhttp.open("GET", "templates/Client/products.json", "true");
xmlhttp.send();
}
}
this function add rows to the table
function addItem() {
items++;
// code...
var html = "<tr>";
html += "<td><input type='text' class='form-control' name='product[]' list='produit' id='pick' onchange='showAmount(this.value)' ><datalist id='produit'> <?php foreach ($productinfo as $req) { ?><option value='<?php echo $req['NomArt']; ?>'><?php echo $req['NomArt']; } ?></option></datalist></td>";
html += "<td class='text-center qte'></td>";
html += "<td><input type='number' class='form-control' name='qte[]'></td>";
html += "<td><button type='button' class='btn btn-danger' onclick='remove(this);'><i class='fa fa-close'></i></button></td>";
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
`
And i couldn't understand others exactly as they showed jquery with Ids and stuff. is there a way to do it with php cuz php approach also gave the same results showing the amount of the last product that's why i took javascript approach but couldn't get a handle of it.
It would help to see your response, but I think the problem is that you're checking one product and updating all rows. You need to identify which row to update, and if your user puts the same product name in two different rows, your system will be confused, so start by changing your function call to onChange="showAmount(this)", so you're passing a DOM element rather than text.
function ShowAmount(productInput) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
myObj = JSON.parse(this.responseText);
row = productInput.parentElement.closest('tr'); // find the table row
let i = myObj.map(item => item.NomArt).indexOf(productInput.value); // find matching data in response
row.getElementsByClassName('qte')[0].innerHTML = myQbj[i].Qte // update the row
}
xmlhttp.open("GET", "templates/Client/products.json", "true");
xmlhttp.send();
}
Of course, you're downloading the entire product catalogue every time the user makes a single change. If your database is large, this is very inefficient. You'd be better updating your back end to return data on a specified product.
xmlhttp.open("GET", "templates/Client/products.json?product="+productInput.value, "true");
I've completed the question before. However I got another issue. I want to make multiple autocomplete like https://jqueryui.com/autocomplete/#multiple .
I've include function into my script but still doesn't work.
This is html email form code
<div class="input_container">
<input type="text" id="contact_id" name="sender" onkeyup="autocomplet()" size="95">
<input type="hidden" id="client_id" value="<?php echo $id_client; ?>">
<ul id="contact_list"></ul>
This javascript script
function autocomplet() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#contact_id').val();
var cid = $('#client_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_email_refresh.php',
type: 'POST',
data: "keyword="+keyword+"&cid="+cid+"",
success:function(data){
$('#contact_list').show();
$('#contact_list').html(data);
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
}
});
} else {
$('#contact_list').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#contact_id').val(item);
// hide proposition list
$('#contact_list').hide();
}
ajax_email_refresh code
$keyword = '%'.$_POST['keyword'].'%';
$cid = $_POST['keyword2'];
$sql = "SELECT * FROM contact WHERE contact_name LIKE (:keyword) AND id_client = (:cid) ORDER BY contact_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$contact_name = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['contact_email']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['contact_email']).'\')">'.$contact_name.'</li>';
}
I am not sure if I understood correctly what you are looking for. I have included an example that will help you get started. The timer I have included is to minimize the amount of ajax request you will be doing. Instead of making a request on after every single key stroke, it actually waits 250 milliseconds after the last stroke has been made to run your ajax.
var object = [{'key': 'value1'}, {'key': 'value2'}];
var timer;
function autocompletion(element){
clearTimeout(timer);
timer = setTimeout(function(){
var options = element.nextElementSibling;
options.innerHTML = '';
for(var i = 0; i < object.length; ++i){
var li = document.createElement('li');
li.innerHTML = object[i]['key'];
options.appendChild(li);
}
options.style.display = 'block';
}, 250);
}
<div class="input_container">
<input type="hidden" id="id_client" name="id_client" value="<?php echo $id_client; ?>">
<input type="text" id="contact_id" name="sender" onkeyup="autocompletion(this)" size="95">
<ul id="contact_list" style='display: none'></ul>
<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
alert(comment);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>
How to get textarea tag and input tag id for javascript function ?
Both tag show in while loop so i want every textarea and input tag has different id.
If you generate dynamic id in text box that time if change something in text box that time store it's id in local variable and use it on in your code
<input type = "text" class="textBox" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
var Id
$(document).on('change', "input.textBox", function () {
Id = $(this).attr("id");
alert(Id )
});
Hope this code can help you..
In jQuery, select the tag and use the .each():
$("textarea").each(function(){
alert($(this).attr("id"));
alert($(this).val());
});
$("input").each(function(){
alert($(this).attr("id"));
alert($(this).val());
});
Demo here (Client side).
so first you set the different IDs and then you fetch it.
var textAreaId = $('textarea').prop('id);
var inputId = $('input').prop('id);
Update
$i is constant for every single set of textarea and input combined together.
If you want to grab every set of textarea and input, you should rather assign the ID to instead of doing it for every textarea and input element.
<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan ="2" id='.$i.'"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" name = "comment"></textarea> <br />';
echo '<input type = "text" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(){
var comment = $(this).closest('td').find('textarea').val();
var alertid = $(this).parent().prop('id');
alert(comment);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>
Try this one:
(See JsFiddle working demo)
<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform(this)" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(form){
var comment = $(form).find("textarea").val();
alert(comment);
var alertid = $(form).find("input[name=alertid]").attr("id");
alert(alertid);
//Or if you mean:
var alertid = $(form).find("input[name=alertid]").val();
alert(alertid);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>
i have display data from xml file to the index.php like this
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent=='image')
{
echo '<div><img src="'.$data.'" ></div>';
echo '<div>';
echo '</div>';
}
elseif($agent=='id')
{
echo '<div class = "Left">';
echo '<input type = "button" name="Agent" id = "'.$data.'" class = "subs-btn" value = "Select this Agent" OnClick = Selected(this.id);>';
$_SESSION['Selected'] = $data;
echo '</div>';
echo '<br/>';
echo '<br/>';
}
else
{
echo '<div class = "inline1">';
echo $data;
echo '</div>';
echo '<br/>';
}
processXML($data);
}
}
processXML($xml);
you guys can see here i am generating a button and onclick function is call - Selected(this.id);
So here is the code of function
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
}
So due to this agent is selected. Now i had one button at the end of the page
<input type = "submit" name="Continue" class = "btn btn-primary right" value = "Continue">
now i want to display data which is related to selected agent on another page. So how can i display this data with respect to selected agent?
Please Help.
You would need to something along the lines of the following. This is more just psuedo code than an actual working example, as I don't know what you want to display about an agent
Note: I am assuming you have jQuery included.
JS
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
//Start here
var AgentData = ""//something about the agent. their id or some other identifier
//here you would make an ajax call to a php script
$.ajax({
type:"POST",
data: AgentData,
url: "someurl"
});
}
PHP
$_SESSION["AgentData"] = $_POST["AgentData"];
Now you would be able to access that data about the selected agent anywhere as long as there is a valid session.
I have a table that works like this: http://www.datatables.net/examples/api/editable.html without the header sorting, page changing, and search. I have another functionality that allows me to add a row. All of this is done on the same page. The data is drawn directly from a database. I wrote the code generic so it could be used for any table I want to display.
However, I have came across a problem. Let's say an end-user wants to see a list of houses. This list would be drawn from a houses database. Each house has an owner. There is also an owners table. Each owner has an id (primary_key). In the houses table the owner field uses the owner's id to identify the proper owner. Here is where the problem arises. Once the data from the houses table is displayed the owner, for instance, shows up as an id number. Obviously, to the end-user it either is meaningless or at least annoying. I would like to have, in this case the owner's name, the field that is in question to show instead of a "seemingly" meaningless field. I'm posting the relevant code for my predicament.
Also, can I change mySQL booleans through jQuery? What I mean by that is if, for example, a house is not up for rent so the for_rent flag is set to 0 for FALSE. The table will show 0, as that is what is in the table. Can I change that through jQuery? (Find the 0s or 1s and make them say true or false? Any suggestions as to a direction for answering these questions would be great. Thanks.
Here is the relevant code:
PHP to display table:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
while ($row = mysqli_fetch_array($result))
{
$rowid = $row[$fields[0]];
echo "<tr class='edit_tr' id='".$rowid."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td' data-field='".$f."'><span id='".$rowid."' class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox' id='".$rowid."' data-field='".$f."'/> </td>";
}
$rowid++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
$recordid = $rowid;
//close connection
mysqli_close($con);
}
jQuery to live edit table:
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var table = $('body').attr('id');
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = {table:table, id:id, field:field, text:text};
if (field != text)
{
$.ajax({
type: "POST",
url: "classes/table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
jQuery to live add row:
$(document).ready(function()
{
$(".add").click(function()
{
var fieldArray = [];
var $table = $("#table");
var $lastRow = $table.find("tr:last");
var $dataFields = $lastRow.find("td");
$dataFields.each(function() {
fieldArray.push($(this).attr("data-field"));
});
$("#table").each(function()
{
var $table = $(this);
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
var tablename = $('body').attr('id');
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
for(var i = 0; i < n; i++)
{
tds += '<td class="edit_td" data-field="' + fieldArray[i] +
'"><span id="'+ id +'" class="text"> </span><input type="text" class="editbox" id="' +
id + '" data-field="' + fieldArray[i] + '"/> </td>';
console.log('id: ' + id);
}
tds += '</tr>';
var dataString = {table:tablename, id:id};
if($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
$.ajax({
type: "POST",
url: "classes/table_new_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}else {
$(this).append(tds);
}
});
});
});
you will probably want to extend your generic function for generating the html table to include a joined db table if necessary, though that would get messy, so, create a new function for when you need to join 2 db tables.
The sql for retrieving the owners name into the list of houses would go something like (with a guess at what your field names are):
select a.housename,a.street,a.for_rent,b.name from houses a, owners b where a.owner_id=b.id