How do I update the database after page is refreshing in javaScript? - 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);
});
});
});

Related

how do I populate html form fields from a dynamic form dropdown

I am trying to figure out a way to fill html form fields based on the selection of a dynamic form dropdown menu.
I have been looking around and trying to tweek what I have found. So far I am up to filling one of my form fields. But have no gone off piste trying to fill all three, leaving the radio empty when I want it to pick up the 0 value on all my dummy entries and select enable (0)
<option value="<?= $row['ENABLED2'] . " - " . $row['ID2'] . " - " . $row['SOLDTO2'] ?>"> ..</option>
<?php
}
?>
</select>
...
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
});
});
</script>
...
<FORM id='addClient' action='process/process-addclient.php' method='post'>
<input type='text' id='ID2' name='ID2' maxlength='4' placeholder='Four Digit Sage Code' style='display:inline'>
<textarea id='SOLDTO2' name='SOLDTO2' placeholder='Client Name and Address - 6 Lines Max'></textarea>
<input type="radio" name='ENABLED2' id='enable' value='0'> <label for='enable'>Enable Client</label>
<input type="radio" name='ENABLED2' id='disable' value='1'> <label for='disable'>Disable Client</label>
In writing this out I have answered some of my own questions but I cant figure out how to get the last column (radio) to populate.
I am new to JS/JQ
The way to populate the radio field is by using the following code:
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
//Check radio field based on value of GetValueEn
if (GetValueEn == 0) {
$("#enable").prop('checked', true);
}
else {
$("#disable").prop('checked', true);
}
});
});
</script>

Value from textbox gets blank after update

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!

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!

save and read the checkbox value in the db, change the status of the label

I have to use a checkbox as a preference choice, so I save it in a mysql db to have it always available. When I select the chekbox the label changes to Enabled and vice versa. When you save (submit) the page sends an allert message indicating the status of the checkbox, and save the new value in the db 0 = disabled 1 = enabled and "reload" the same page and read the new values. Now I have the problem that the scripts intervene before I can read the value from the db. Only when I reload the page the second time do I get the correct values. I inserted a page refresh but I did not solve the problem.
-js-
<script>
function checked() {
if (document.getElementById("check1").checked){
$(check1).siblings('label').html('Abled');
alert("Abled Notify");
$.get("birthdaysend.php");
} else {
$(check1).siblings('label').html('Disabled');
alert("Disabled Notify");
}
}
// function change label checked
$('#check1').click(function() {
if ($(this).is(':checked')) {
$(this).siblings('label').html('Abled');
} else {
$(this).siblings('label').html('Disabled');
}
});
function urlCheck() {
if(window.location.href=="preference.php"){
//load page = read satus
checked();
}
}
urlCheck()
</script>
-Insert in to db-
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
header("Refresh:0");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
//header("Refresh:0");
}
-Html-
<form name="preference" action="preference.php" method="POST">
<div class="col-sm-4"><label class="container" for="check1">Tag 1</label><input type="checkbox" class="checkmark" name="check1" id="check1" value="1" <?php echo ($dbox == 1 ? 'checked' : '');?>></div>
<button style="float:left; margin-left: 0px;" type="submit" class="btn btn-primary"><i class="fa fa-floppy-o"></i> Save </button>
</form>
First of all change this, make update code first and then select
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
}
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
Remove Urlcheck and checked functions from javascript
In label add this code instead of tag 1
echo ($dbox == 1 ? 'Abled' : 'Disabled');
A better way to do that would be with Ajax where the code to insert the value into a database is a different page from the one with a check box. Ajax is a JavaScript Library that has a synchronous ability.W3Schools tutorial for Ajax

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;
}

Categories

Resources