how to solve theproblem with saving the data in an appended textbox - javascript

please help me out, i use isset to check if the index is defined but instead of saving the value of the textbox it stores 0.how shoul i do it? cause if i wont check if the index is defined ,when i only fill out one textbox it will throw an error, but if i fill out all five it works fine. please take a look at y code, the variables in javascript is used for its inout name, the count is for the stop adding of input text when it reach 5
HTML and PHP
<form class="form-horizontal" method= "POST">
<div class="control-group">
<div class="inc">
<div class="controls">
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<input type="submit" class="btn btn-info" name="submit" value="submit"/>
</div>
<?php
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
if(isset($_POST['submit'])){
for($i=1; $i<=5; $i++){
if(isset($_POST["textbox$i"]) && $_POST["textbox$i"] !=""){
$sasa = $_POST["textbox$i"];
$sql="INSERT into sasa (sasa) values('$sasa')";
echo $sql."<br>";
$q=$conn->query($sql);
}
}
}
?>
javascript;
<script type="text/javascript">
jQuery(document).ready( function () {
var val = 1;
var me = 0;
var count = 0;
$("#append").click( function() {
if(count<5){
if(me==0){
val=1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
else{
val = val + 1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
}
else{
}
});
jQuery(document).on('click', '.remove_this', function() {
me = me - 1;
count = count - 1;
jQuery(this).parent().remove();
return false;
});
});

both your JS and PHP are wrong. You need to post an array rather than naming each textbox. In other words, your textbox names should be something like name='textbox[]'. Redo it like this:
JS:
$(document).ready(function () {
$("#append").click(function (e) {
e.preventDefault();
var textboxes = $(".textbox").length;
if (textboxes < 5) {
$(".inc").append("<div class='controls'>\
<input class='textbox form-control' type='text' name='textbox[]' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
});
});
PHP:
if (isset($_POST['submit'])) {
if (!empty($_POST['textbox'])) {
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
$textboxes = $_POST['textbox'];
foreach ($textboxes as $value) {
$sql = "INSERT into sasa (sasa) values('$value')";
echo $sql . "<br>";
$q = $conn->query($sql);
}
}
}

Ok, it seems like your goal is to send a multidimensional array to PHP. In other words, you want PHP to be able to receive something in this format:
array (size=2)
0 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
1 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
In order for you to achieve this, you need to create a function that indexes your input textboxes when you create them and when you delete them so that you can end up with inputs with indexed name attributes like so:
<input name="data[0][text]">
<input name="data[0][box]">
<input name="data[1][text]">
<input name="data[1][box]">
With that said, this is the JS I would use:
<script>
$(document).ready(function () {
function re_index($cont) {
$cont.find(".textbox_group").each(function (i) {
$(this).find('.text').attr("name", "data[" + i + "][text]");
$(this).find('.box').attr("name", "data[" + i + "][box]");
});
}
$("#append").click(function (e) {
e.preventDefault();
var $cont = $(".inc");
if ($(".textbox_group").length < 5) {
$cont.append("<div class='controls textbox_group'>\
<input class='text form-control' type='text' >\
<input class='box form-control' type='text' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
re_index($cont);
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
var $cont = $(".inc");
re_index($cont);
});
});
</script>
Then in PHP you can capture the data and iterate to insert it with SQL:
$data = $_POST['data'];
foreach ($data as $input) {
var_dump($input['text']);
var_dump($input['box']);
}

Related

Have two variables in one foreach bad insert

Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired
I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}

Javascript Value change not recognised by PHP $_POST

So basically I want to be able to pass a variable from Javascript to php dynamically and without $_GET and preferably without cookies, so I tried using html DOM to change the .value of the html hidden element and then posting it but it won't recognise the value has changed.
for(i=0;i<60; i++) {
pen.push(<?php
$ii += 1;
$sql=mysqli_query($connection, "SELECT Quantity from stockinventory where ID = '$ii'");
while($row = $sql->fetch_assoc()) {
echo(json_encode($row['Quantity']));
}
?>);
}
//fix this
function subStock(cuanto, id) {
pen[id] = pen[id]-1;
document.getElementById(id).innerHTML = pen[id];
document.getElementByName(id).value = pen[id];
}
function addStock(cuanto, id) {
pen[id] = parseInt(pen[id])+1;
document.getElementById(id).innerHTML = pen[id];
document.getElementByName(id).value = pen[id];
}
</script>
$search = mysqli_query($connection, "SELECT * from stockinventory WHERE categody LIKE '%$empanada%'");
echo("<form action='admin.php' method='POST'>
<input type='submit' name='Juan'>");
while($row = $search->fetch_assoc()) {
echo("<div class='wrapper' id='wrap'>
<div class = 'dynamo' style= background-image:url(".$row['imagee'].")>
<h2>".$row['Name']."</h2>
<div class='slider' id='slider'>
<p id='rat'>".$row['Description']."</p>
<button type='button' onClick='subStock(".$row['Quantity'].",". $i.")' id= 'jose' name= 'Alma'>-</button>
<a id=".$i.">".$row['Quantity']."</a>
<button type='button' onClick='addStock(".$row['Quantity'].",". $i.")' id= 'jose' name= 'Alma'>+</button>
<form method='POST' action='admin.php'>
<input type='hidden' id= G".$i." value = 10 name = ".$i." >
</form>
</div>
</div>
</div>");
$i+=1;
}
if(isset($_POST['Juan']))
{
//for($c = 0; $c<39; $c++ ) {
$c = 1;
$quant = $_POST[$c];
echo($_POST[$c]);
$dql = mysqli_query($connection, "UPDATE stockinventory
SET Quantity = $quant
WHERE ID = '$c'");
}

Edit input name when chceckbox clicked

I try to edit name field for the specific input. I need this to get all the variables from this site and add them to my invoice script. I have two divs with client select and service select
HTML:
<div class="service-select">
<?php
$query = "SELECT id,service_name,quantity,net_price,gross_value FROM service";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<div class='single-service-<?php echo $row["id"]; ?>'>
<input type='checkbox' name=''>
<input type="text" name="service_name" class='name' value="<?php echo $row["service_name"]; ?>" placeholder='NAZWA USŁUGI' disabled/>
<label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
<label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
</div>
<?php
}
$result->free();
}
?>
</div>
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i=0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var div = this.parentNode;
var name_input = div.getElementsByClassName("name");
var name = name_input.name;
var parent_div = div.parentNode;
var x = div.childNodes;
console.log(name_input);
if (parent_div.className == 'service-select') {
if (name_input.name != 'service_chcecked[]') {
name_input.name = 'service_chcecked[]';
}
else {
name_input.name = 'service_name';
}
}
else {
if (name != 'client_chcecked[]') {
name_input.name = ['client_chcecked[]'];
}
else {
name_input.name = ['client_name'];
}
}
for(y=0; y < x.length; y++) {
if(x[y].type === "number" || x[y].type === "text") {
x[y].disabled = !x[y].disabled;
}
}
}, false);
};
My problem is that currently the given name is added to the div :/

multiple textbox values storing in same column in php

I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop

autosave checkboxes on click

I have my forms in a loop gerating many forms with checkboxes.The choices are submitted via a hidden iframe that runs my php.Can i make this checkboxes autosave to the database ?
<form action='http://www.toppromomkt.com/wp-content/themes/toppromo/insert_wallet.php' method='post' class="my-form" target='hidden-form'>
<input class="styled" type='checkbox' name='pago' value='yes' <?php if ($che=='yes') {echo "checked='yes'"; } else if ($cccc='') {} else {} ; ?> > <br> </div><div class='tb1 tb1_small sc' >
<input class="styled" type='checkbox' name='recibo' value='yes' <?php if ($rec=='yes') {echo "checked='yes'";} else{}; ?> > <br></div><div class='tb1 tb3_md sc '>
<input class="styled" type="hidden" name="contador" readonly value="<?php echo $id_postt1."linha_".$events[0]; ?>">
<input class="styled" type="hidden" name="id_p" readonly value="<?php echo $events[2];?>">
<input type='Submit' class="button white small" value='Salvar' onclick='saved(<?php echo $fid ?>)' />
</form>
You can create a setInterval which will be initialized on click of checkbox and will make an ajax request to save it to DB.
Following is a sample code:
Code
JSFiddle
var formCount = 1;
var saveInterval = null;
var data = []; // Used to mimic DB
function createForm() {
var html = "<form id='frm_" + formCount + "' >"
for (var i = 0; i < 5;) {
html += "<input type='text' name='input_" + ++i + "' /> <br/>";
}
document.getElementById("content").innerHTML += html;
formCount++;
}
function autoSaveInit(el) {
if (el.checked) {
if (!saveInterval) {
saveInterval = setInterval(function() {
saveData();
}, 3000);
}
} else {
window.clearInterval(saveInterval);
saveInterval = null;
}
}
function saveData() {
var forms = document.getElementsByTagName("form");
var _tempObj = {};
// Reset Data for Demo purpose.
data = [];
for (var i = 0; i < forms.length; i++) {
_tempObj = new Object();
_tempObj.formID = forms[i].id;
_tempObj.data = [];
var inputs = forms[i].getElementsByTagName("input");
for (var j = 0; j < inputs.length; j++) {
var name = inputs[j].name;
_tempObj.data.push({
"name": name,
"value": inputs[j].value
});
}
data.push(_tempObj);
}
console.log("Save Completed: ", data);
}
Following is a sample for generating form with auto-save;
<div id="content"></div>
<button onclick="createForm()">Create Form</button>
<input type="checkbox" id="chkAutoSave" onclick="autoSaveInit(this)">
<label for="chkAutoSave">Auto save forms?</label>

Categories