Can't select element's value loaded by PHP from Database - javascript

I have enlisted data from database using PHP. I'm unable to select element's value. Although the data is loaded in DOM. If i just write HTML markup then i'm able to select it other
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" onsubmit="return false">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color" class='product_color'>
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" class='product_qty' id='product_qty' value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button class="add_to_cart" id='add_to_cart' type='submit'>Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
Here's the javascript im using.
window.onload = function () {
$('.add_to_cart').click(function(){
$parent = $(this).parent();
$qty = $parent.children('.product-desc').text();
alert($qty);
})
};
Above code works, if i just use HTML Markup rather using above HTML generated using PHP.
Thanks in advance. Searched a lot for this but didn't find anything relevant. Although i also tried Javascripts '.on' and '.live' function but they didn't worked.

$parent = $(this).parent(); selects the <div align="center"> around the button. Use $parent = $(this).closest('.product'); instead.
Though I would recommend actually binding to the submit event of the form instead of to the click of the button.

Related

Form is auto submitting but the data is not getting passed/received

I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}

how to interact with specific forms (that are dynamically created) when there are multiple forms on the page?

I have a page that contains multiple forms that are dynamically created based on the users input, so a page can have just one form or many. The forms consist of two sets of radio buttons, the second set is disabled by default and is enabled based on the users choice in the first set of radio buttons.
This part works absolutely fine, when the user makes the appropriate selection from the first question the second question is made available. However, this applies to all the forms at the same time, so when the selection is made on form 1 all the other forms react based on form 1's input.
Each form has a dynamic class using the id from the database so how do I tell jquery which form the user is interacting with? So that when the user makes a choice on one form it only affects the second set of questions on that particular form?
$(document).ready(function() {
$('.mealSection').prop('disabled', true).css('opacity', '.2');
$('.attendRadio').change(function() {
if ($(this).val() === "Attending") {
$(".mealSection").prop('disabled', false).css('opacity', '1');
} else {
$(".mealSection .mealRadio").prop('checked', false);
$('.mealSection').prop('disabled', true).css('opacity', '.2');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="processRSVP.php" method="post" class="rsvpForm[<? echo $r['GuestID']; ?>]">
<fieldset class="attendSection">
<input type="hidden" value="<? echo $r['GuestID']; ?>" name="id">
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Attending">Hell Yeah!
</div>
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Not Attending">...Nah
</div>
</fieldset>
<fieldset class="mealSection">
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 1">Option 1
</div>
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 2">Option 2
</div>
</fieldset>
<div class="rsvpButtonContainer">
<input type="submit" name="<? echo $r['GuestID']; ?>" value="confirm">
</div>
</form>
<form action="processRSVP.php" method="post" class="rsvpForm[<? echo $r['GuestID']; ?>]">
<fieldset class="attendSection">
<input type="hidden" value="<? echo $r['GuestID']; ?>" name="id">
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Attending">Hell Yeah!
</div>
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Not Attending">...Nah
</div>
</fieldset>
<fieldset class="mealSection">
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 1">Option 1
</div>
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 2">Option 2
</div>
</fieldset>
<div class="rsvpButtonContainer">
<input type="submit" name="<? echo $r['GuestID']; ?>" value="confirm">
</div>
</form>
I get that at the moment all that my jquery is doing is waiting for a change of state on the first radio buttons and that it doesn't care which form the change comes from. I've tried using focus but my understanding is that only works with the form elements not the actual form itself? I've tried looping through each form but that doesn't seem to work either, although I have a feeling that I'm just going about it all wrong.
Any help at all is greatly appreciated, just a nudge in the right direction would be great.
If your callback takes a event argument you can access the element the user is interacting with with event.target1 and you can access the containing form using the parents2 jQuery method and from there you can call find3 on the form element to specifically access only elements inside of it:
$('.attendRadio').change(function(event) {
var formEl = $(event.target).parents('form');
if ($(this).val() === "Attending") {
formEl.find(".mealSection").prop('disabled', false).css('opacity', '1');
} else {
formEl.find(".mealSection .mealRadio").prop('checked', false);
formEl.find('.mealSection').prop('disabled', true).css('opacity', '.2');
}
});
[1] https://developer.mozilla.org/en-US/docs/Web/API/Event/target
[2] https://api.jquery.com/parents/
[3] https://api.jquery.com/find/

How to do a page refresh after submitting and executing an update statement to show the updated values?

I have to click on the update button and then do an update in database and a refresh to show the updated values on the same page. These values must be updated in the database as well. I have been trying to do the refresh but it does not work. Need some help and guidance. Is there any other alternative besides page refresh? Can it be done without page refresh?
<?php
//initalizing the query
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" onclick="window.location.reload();"/>
</form>
</div>
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
header("Refresh: 0; url=previewgraphs.php?id=".$id);
}
?>
UPDATED:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="previewgraphs.php?id=$id" method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
Please take updated value from the database after update query.
Please try this code :-
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
$select_query = "SELECT * FROM new_default_reports where id = $id";
$select_result= $conn->query($select_query );
$row = $select_result->fetch_assoc();
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
The header function does not work in your case because you have already output before trying to set the header.
The solution is to reverse the php and html code such that the php code is on the very beginning of the document.
Little side note, now you actually do not need the refresh anymore.
EDIT included select query.
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
//header("Refresh: 0; url=previewgraphs.php?id=".$id);//not needed
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
$row = $select_result->fetch_assoc();
}
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
And remove onclick="window.location.reload();"
Here is how I would do it:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold"">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_axis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
So you wouldn't need to refresh the page, but rather you send the form to itself. It will result in another request. If the form has been sent the php code in the if-clause get executed and the database will be updated. Than you have the task to make a select query to get the updated result and display it on the page.
Should the user open the page with the form per get request, she is not going to see any results from the database.
When writing HTML you should also try to be consistent and keep the code conventions throughout your project. For single tags XML-like style is <input \>, HTML-style is <input>.
I hope this helps you and also gives you some alternative view how to solve your problem.
EDIT:
I removed the onclick event from your input element and added a submit button. When checking if the form has been sent, look for the submit button in your if-clause. If you like you can use <button type="submit">Submit the form</button> instead of <input type="submit">
ANOTHER EDIT:
I added simple select query and displayed the updated report on the page.
This is my idea about it:
user sends GET request - form is displayed
user sends POST request (submitting the form) - it is sent to itself, the from is displayed and the user gets feedback if update was successful, the udpated values being displayed
When creating something like this I always think on CRUD - create, retrieve, update, display.
The form should update an entry in the database.
For the retrieve part you should better use another view, displaying only the result, but not the form.
You could certainly send the form to the page where the result is displayed*, but I think that would be a bad practice. The user needs some feedback if the update action was successful.
for example something like this:
<form action="<?php echo 'previewgraphs?id=$id'; ?>">
You shouldn't squeeze to much logic into one part. Rethink your design. I'd also reccomend you to use a framework that implements the MVC pattern. You have a big choice. The framework will take care about many things and provide you also semantic URLs, so you'll have something like:
/reports
/reports/1
instead of appending all the parameters to the URL.
first restructure your code.
The first part of your code must save the values in case changes are being submitted. Then you read from the database again and show results.
However this could be a browser or proxy caching problem. I have a couple of tags that have been very helpful:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="cache-control" content="no-cache">
put them in the html < head > section . Older IEs do weird things with proxys sometimes.
Cheers, Karsten

Check if input field empty

I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.

Getting values of multiple $_POST elements

I am creating a form that allows the user to supply additional addresses they are located at. I have a drop down that asks "How many additional locations do you have?" based on the number they select I clone the fields "Address, City, State, Zip" and place them directly underneath of each other inside the same form.
What I described above is working but now I am attempting to retrieve the data from these additional fields I added. When the user clicks the submit button the form submits to the same page where I have PHP listening to see if the form has been submitted or not. If it has been submitted I echo the values of the form to the screen.
Now here is the problem. If I leave the dropbox alone so that it is at the default value of "1" fill out the form and click submit I see what I entered. But if I select any other value from the drop down and submit the information from all of the forms I only see the information from the last form and not all of them. Why is this? I have included my code below.
Here is the form :
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional">
<legend>Additional Locations</legend>
<p><label for="Address">Address</label> <input name="Address" type="text" id="Address" /><br /></p>
<p><label for="City">City</label> <input type="text" name="City" id="City" /></p>
<p>
<label for="State">State</label>
<select id="State" name="State">
<option selected="selected">Select your state...</option>
<?php foreach($states as $key=>$value) { ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
</p>
<p><label for="Zip">Zip Code</label><input type="text" name="Zip" maxlength="6" /></p>
<p><label for="Country">Country</label><select id="Country" name="Country">
<option value="US" selected="selected">United States</option>
<option value="CA">Canada</option>
</select></p>
<input type="submit" value="SUBMIT FORM" />
</fieldset>
</div>
</form>
This is how the fields are created based on the dropdown
var cloneIndex = 0,
cloneObj = $('.additional').eq(0);
$(document).on('change', "#NumberOfLocations", function() {
if ( $(this).val() !== "" ) {
for( var x = 2; x < $(this).val(); x++ ) {
$('#AdditionalLocations').append( cloneObj.clone( true ).attr('' ,'data-index', ++cloneIndex) )
}
}
});
This is how I echo the results of the form. It works if I don't create new additional fields based on the drop down.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
var_dump($_POST);
foreach( $_POST as $field ) {
if( is_array( $field ) ) {
foreach( $field as $field2 ) {
echo $field2;
}
} else {
echo $field2;
}
}
}
?>
If I select 2 as the value in the number of locations field this is the html output I get:
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional"></fieldset>
<fieldset name="first" class="additional" data-index="1"></fieldset>
</div>
</form>
Inside the fieldset all of the fields are identical. Why do I not get both fieldsets echoed when I click submit?
UPDATE:
So I changed the names of the second field set by adding a "1" at the end inside the chrome inspector and submitted now I see all of the values I need. So I guess every field in the form has to have a unique name.
your field names should have array notation at the end of their names:
<input type="text" name="City[]" id="City" />
<select id="State" name="State[]">
when php gets these values they will then be in array so you will need to loop over each of the arrays to get the info
for($i=0; $i<count($_POST['City']); $i++){
$city = $_POST['City'][$i];
$state = $_POST['State'][$i];
...
}
There is probably a better way of getting the info out of the arrays, but this is quick and dirty

Categories