Value from textbox gets blank after update - javascript

I have this edit link (name) where the value from the database gets transformed to textbox when clicked. The problem is when I update other normal textbox (age), the value from the edit link textbox becomes blank. But when I input a value into the edit link textbox, the value is saved. Why is it that everytime I update other textbox, the edit link textbox value becomes blank? Please help
$(document).ready(function() {
$('a.edit').click(function (e) {
e.preventDefault();
var dad = $(this).parent().parent();
dad.find('label').hide();
dad.find('input[type="text"]').show().focus();
return false;
});
$(".edit-input").focusout(function() {
var dad = $(this).parent();
$(this).hide();
dad.find('label').show();
});
$sql = "SELECT * FROM details";
$result = mysqli_query($conn,$sql);
while ($rowwaf = mysqli_fetch_assoc($result)) {
echo "<td><label for=\ "name\" class=\ "control-label\">
<p class=\"text-info\" style=\"color: black\">".$rowwaf["name"]."</p></label>
<input type=\ "text\" class=\ "edit-input\" name=\ "name\" placeholder=\ " ".$rowwaf[ "name"]. " \" maxlength=\ "10\" />
<div class=\ "controls\">
<a class=\ "edit\" href=\ "#\">Edit</a>
</div>
echo "<td ><input size=\"18\" type=\"text\" name=\"age\" value=\"".$rowwaf["age"]."\"></td>\n" ;
</td>";
My update query:
$name = $_POST["name"];
$age = $_POST["age"];
$id = $_POST["id"];
$updquery = "UPDATE details
SET name = '$name', age = '$age'
WHERE id = '$id'";
$result = mysqli_query($conn,$updquery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I guess the problem is with the echo statement from php.
<input type="text" class="edit-input" name="name" placeholder="$rowwaf["name"]" value="$rowwaf["name"]" maxlength="10" />
You are setting placeholder, I guess you also need to set the value attribute to the input tag.
If it doesn't help, try including a running snippet. Maybe we could do something about it then!

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!

get radio button value (PhP MySQL and ajax)

Newbie here..
I have this code for my displaying the database records in a table,
I want to know how do i get the value of radio button (the radio button contains the id of selected row). I tried doing it in javascript but no luck.
table.php
<table border="1">
<th></th>
<th>Particulars</th>
<th>Amount</th>
<?php
include('includes/config.php');
$qry = $con->prepare('SELECT * FROM fees');
$qry->execute();
$row = $qry->rowCount();
while ($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$id = $row['fee_id'];
$fee = $row['fee_name'];
$amt = $row['amount'];
?>
<?php echo "
<tr title='Click to edit or delete record'>
<td><input type = 'radio' name = 'radio' class ='radio' value = $row[fee_id]></td>
<td>$fee</td>
<td>$amt</td>
</tr>
"; ?>
<?php } ?>
</table>
<input type="button" value="Delete Selected Fee" style="width:250px; height:40px;font-weight:bold;" onclick="delete();"><br><br>
javascript code
<script type="text/javascript">
function delete(){
if (document.getElementsByClassName(this.class).checked){
var val = document.getElementsByClassName(this.class).value;
alert (val);
}
}
</script>
Use this
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
console.log(val);
}
}
I suggest you to use hidden field instead if you don't want to show. The property of radio buttons is to show only true / false value. It may be on / off or yes / no, according to your uses. Use like
<input type = 'hidden' name = 'whatever' class ='radio' value =<?php echo $row['fee_id']; ?>>
You can try this, this should get your radio button value using your input name.
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
Following code will give you your radio button value
<script type="text/javascript">
function delete(){
if($('input[name="radio"]').is(':checked')){
var val = $('input[name="radio"]').val();
alert (val);
}
}
</script>
you can use console.log(val);

How do I update the database after page is refreshing in javaScript?

I want give the opportunity to the user to change the rating value of a product, but it is not working after refreshing the page. For example, when he goes to a new product that he did not rate, he can change the rating value again and again before refreshing the page. But after refreshing the page he can change the rating value of the same product, but the alert for the "ratingValue2" is not working and the database is not updating.
Here is my PHP code.
$jsqla3 = mysql_query("select * from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$jfeta3 = mysql_fetch_assoc($jsqla3);
if($jfeta3 != null) {
$ratea = $jfeta3['rate_value'];
}
Here is my HTML code.
<input class="rating form-control input-star-rate" id="<?php echo $rateid; ?>" name="rating" value="<?php echo $ratea; ?>" data-min="0" data-max="5" data-step="0.3" data-size="xs" style="display: none; text-align: center;"/>
Here is my javaScript code.
$(function(){
$(document).ready(function(e) {
var $stars = $('.input-star-rate');
$stars.bind('change', function() {
var $this = $(this);
var ratingValue = $this.val();
var ratingValue2 = parseFloat(ratingValue);
alert(ratingValue2);
});
});
});

php javascript change innerHTML with select value from table

I've got a form with a input field(FIELD1). When the user types in FIELD1 it filters values in FIELD2. Then they click on FIELD2 and it display's the value selected via javascript (this tutorial: http://www.tizag.com/javascriptT/javascript-innerHTML.php). The problem I'm having is that the value of FIELD2 is the companyID in the table - how do I include the javascript to lookup the company name from the table. Picture attached.
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('cv_bus').value;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}
</script>
<table style="width:500px;border:1px solid #000;">
<tr><td>2</td><td>Type in the box below to narrow the list of names:</td></tr>
<tr><td></td><td><input type="text" name="filterTxt" id="filterTxt" tabindex="2" style="width: 400px"></td></tr>
<tr><td></td><td><p>SELECTED: <font color=red><b id='boldStuff2'>NONE</b> </p></font></td></tr>
<tr><td></td><td>Select the apropriate name:</td></tr>
<tr><td></td><td><select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2()">
<?php
include 'cv_con.php';
$get = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
$result = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
//$option = '';
while($row = mysqli_fetch_array($result)) {
$option .= '<option value = "'.$row['id'].'">'.$row['compname'].'</option>';
}
?>
<?php echo $option; ?></select>
var el = document.getElementById('cv_bus');
var text = el.options[el.selectedIndex].innerHTML;
Try this example, first get the ID then access to the options label.
replace this
var userInput = document.getElementById('cv_bus').value;
with
var userInput = cv_bus.options[cv_bus.selectedIndex].text;
another way is pass this in function:
<select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2(this);">
function changeText2(selObj){
var userInput = selObj.options[selObj.selectedIndex].text;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}

Retrieving values from data base, store in input text and textarea, change, pass new one to DB using PHP?

I'm Trying to change the values in the database using PHP and MySQL.
I am getting the values from database and storing them in placeholder for each input but when i submit the form again it submit the inputs with empty values, i tried storing them in Value attribute for each input again the old value is overwriting what i write in the input field so nothing in the database change.
How can i keep the old value in the input fields but in case the content of these fields changed the new value is passed back to the database instead of the old one.
Here is my Code :
function list_products () {
$get = mysql_query('SELECT `id`, `SKU`, `sub`, `pname`, `desc`, `price`, `ship`, `qty`, `cat` FROM `products` ORDER BY `id` DESC');
if (mysql_num_rows($get) == 0) {
echo "There are no product to display!";
} else {
while ($get_row = mysql_fetch_assoc($get)) {
echo
'<h5>'.$get_row['pname'].' id: '.$get_row['id'].'</h5>
<form action="delete_product.php" method="post">
<input type="hidden" value="'.$get_row['id'].'" name="id">
<input type="submit" name="submit" value="DELETE" class="btn btn-lg btn-danger">
</form>
<form action="update_p.php" method="post">
<input type="hidden" placeholder="'.$get_row['id'].'" name="id" value="'.$get_row['id'].'">
<label>SKU:</label>
<input type="text" placeholder="'.$get_row['SKU'].'" name="SKU" value="'.$get_row['SKU'].'" required="">
<label>Name:</label>
<input type="text" placeholder="'.$get_row['pname'].'" name="pname" required="" value="'.$get_row['pname'].'">
<label>Subtitle:</label>
<textarea rows="2" maxlength="46" name="desc" placeholder="'.$get_row['sub'].'" required="">'.$get_row['sub'].'</textarea>
<label>Description:</label>
<textarea rows="4" name="desc" placeholder="'.$get_row['desc'].'" required="">'.$get_row['desc'].'</textarea>
<label>Price:</label>
<input type="text" placeholder="'.number_format($get_row['price'], 2).'" name="price" value="'.number_format($get_row['price'], 2).'" required="">
<label>Shipping:</label>
<input type="text" placeholder="'.number_format($get_row['ship'], 2).'" name="ship" value="'.number_format($get_row['ship'], 2).'" required="">
<label>Quantity:</label>
<input type="text" placeholder="'.$get_row['qty'].'" name="qty" value="'.$get_row['qty'].'" required="">
<label>Category:</label>
<input type="text" placeholder="'.$get_row['cat'].'" name="cat" value="'.$get_row['cat'].'" required=""><br>
<input type="submit" name="submit" value="EDIT" class="btn btn-success btn-lg">
</form>
<hr>
';
};
}
}
The update_p.php page:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$update_data = array(
'pname' => $_POST['pname'],
'desc' => $_POST['desc'],
'price' => $_POST['price'],
'ship' => $_POST['ship'],
'qty' => $_POST['qty'],
'cat' => $_POST['cat']
);
update_product($id, $update_data);
The update_data function :
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `products` SET " . implode(', ', $update) . " WHERE `id` = $id");
}
#MaveRick Thanks for the effort, but my question is how to overwrite the value of the input fields on the page before we send the information to the server, i think its can be done using JavaScript more than php, however to make more clear these input fields refers to values in the database already stored and i would like to give the option for the user to change them in his admin panel by retrieving the content of these fields from the database and print them in the actual input fields so in case the customer pressed edit(submit) with out touching anything the same values will be sent again to the database this way nothing will be change, and in another case where the customer added or changed any value in any of these fields then the new value will be passed. hopefully i clarified my issue now. Thanks for your help anyway.
#Prafful Garg i already tried the value field but it didn't work thanks for your help anyway
You can retrieve the data again from the database in file update_p.php as follow:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM `products` WHERE `id` = '$id';");
$get_row = mysql_fetch_assoc($get);
$update_data = array(
'pname' => (empty($_POST['pname'])?$get_row['pname']:$_POST['pname']),
'desc' => (empty($_POST['desc'])?$get_row['desc']:$_POST['desc']),
'price' => (empty($_POST['price'])?$get_row['price']:$_POST['price']),
'ship' => (empty($_POST['ship'])?$get_row['ship']:$_POST['ship']),
'qty' => (empty($_POST['qty'])?$get_row['qty']:$_POST['qty']),
'cat' => (empty($_POST['cat'])?$get_row['cat']:$_POST['cat'])
);
update_product($id, $update_data);
But this is not a professional way to do it.
What you can do is a loop to create the update statement and test each input; if not empty then add to the update statement , name=value otherwise to skip this input and process the next one in the array POST. something similar to the following:
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$query = "UPDATE `products` SET `id` = '$id'";
foreach($update_data AS $k=>$v){
if(!empty($v) && strlen($v)>0)
$query .= ", `".$k."` = '".$v."'";
}
$query .= " WHERE `id` = '$id';";
mysql_query($query);
}
IMPORTANT NOTE: mysql() is vulnerable and deprecated, please try to avoid using mysql() and use mysqli() or dbo() extensions instead.

Categories

Resources