buttons in forms doesnt work after ajax call from db - javascript

I have search google, here and w3schools but this answer i cant find anyway. Not even in the "questions that may already have your answer".
I am trying to learn a bit more about AJAX and i have come to a hold at this guide W3schools AJAX database
All the guide i can get to work but when i try to suit it to my needs it goes wrong. What i want is that when i get to "getuser.php" i want to be able to update db in this file. If possible without me leaving this page with the result i have found. I choose from a dropdown table before this site. The php files which is supposed to update the db works (tried them on a normal page, and all is good). My current workaround is to add a button which opens a second window to update the info.
When i get to this point:
<?php
$q = intval($_GET['q']);
include 'db.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"webhelp");
$sql="SELECT * FROM advisors WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<table><tr><td>Phone</td><td>" . $row['phone'] . "</td>
<td><form action='addphone.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><input type='text' name='phone'></td>
<td><input type='submit' value='Update'></td>
</form></td></tr></table>";
echo "<tr><td>LoB</td><td>" . $row['lob'] . "</td>
<td><form action='addlob.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><select name='lob'>
<option value='". $row['lob'] ."'>" . $row['lob'] . "</option>".
$sql = "SELECT * FROM lob";
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["lob"] . "'>" . $row["lob"] . "</option>"; }
"</select></td>
<td><input type='submit' value='Update'></td>
</form>
</tr>";
echo "<tr><td>Country</td><td>" . $row['country'] . "</td>
<td><form action='addcountry.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><select name='country'>
<option value='". $row['country'] ."'>" . $row['country'] . "</option>".
$sql = "SELECT * FROM country";
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["country"] . "'>" . $row2["country"] . "</option>" ; }
"</select></td>
<td><input type='submit' value='Update'></td>
</form>
</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The "Update" buttons doesnt work. It doesnt matter where i place the files (same folder, different folder) ect. However if i add a button with a link outside of the then that button work. But as soon as it is inside a table PLUS also method="post" is in the form it mess it up.
What am i doing wrong?
Alternatively is it possible to make a button here which carries the $id over to a small popup window? (I can open it in a new window but I can't choose how big the window should be)

You want to do this for all your 3 forms. I give you example for first one.
Form
echo "<form class='addPhoneForm' action='addphone.php' method='post'>
<table>
<tr>
<td>Phone</td><td>" . $row['phone'] . "</td>
<td><input class='phoneID' type='hidden' name='id' value='".$q."'></td>
<td><input class='phoneNumber' type='text' name='phone'></td>
<td><input class='submitme' type='submit' value='Update'></td>
</td>
</tr>
</table>
</form>";
AJAX
$(document).ready(function(){
$(".submitme").click(function(){
//collect variables from input
var phoneID = $(".phoneID").val();
var phoneNumber = $(".phoneNumber").val();
// store in a string
var dataAddPhone = 'phoneID='+ phoneID + '&phoneNumber='+ phoneNumber;
// send to database
$.ajax({
type: "POST",
url: "addphone.php",
data: dataAddPhone,
cache: true,
//if success
success: function(response){
//display message
$(".displayMessage").html(response);
//and reset form
$(".addPhoneForm").trigger("reset");
}
});
return false;
});
});

Related

Order Button on each row of a table

I have a table of items and I would like to place an order button at the end of the table. The button would then take user to "order.php". Where based on the "Picture ID" they would then order the selected item. I've had a look at similar questions online however haven't been able to get it working with what I currently have.
if ($result->num_rows > 0)
{
echo "<table>\n";
while($row = $result->fetch_assoc())
{
echo "<tr>\n";
echo "<td>". $row["Picture ID"]."</td>\n";
echo "<td>". $row["name"]."</td>\n";
echo "<td>". $row["doc"]."</td>\n";
echo "<td>". $row["width"]."</td>\n";
echo "<td>". $row["height"]."</td>\n";
echo "<td>". $row["price"]."</td>\n";
echo "<td>". $row["description"]."</td>\n";
echo "<td> <form action='order.php' method='post'> <input type='button' name='id' value= ></form>"
echo "</tr>\n";
}
echo "</table>\n";
}
You have to pass the picture id as hidden input text and use the "submit" type for the button:
echo "<td> <form action='order.php' method='post'> <input type='hidden' name='id' value='" . $row["Picture ID"] . "'/> <input type='submit' name='submit' value='Buy'/></form>"
In order.php you can get the Picture ID from $_POST:
if (!empty($_POST['submit'])) { // submit button was pressed
echo 'Picture ID: ' . $_POST['id'];
}
Make sure to escape the $_POST['id'] properly when using it in SQL queries.

How Add select box Dynamically, which retrieve data from Database

I have problem with Web Development,
i have added drop down list using PHP, MySQL and HTML. Now i want to use button and dynamically generate same Select box again and again. How can i do this, please help me..
Here is my Select Box Code.
<Select name="txt-computer_sn" class="form-control" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
if the data of dropdown will remain same then you can do that in this way
html and php
<Select name="txt-computer_sn" class="form-control dynm_drop" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
jquery
$("#buttonid").click(function(){
$(".dynm_drop").clone().appendTo("class or id of element");
});
Try this:
<div class="select_wrapper">
<select name="txt-computer_sn[0]" class="form-control" id="txt-computer_sn_0">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
<input type="button" name="add_select" class="add_select" value="Add New">
</div>
<script type="text/javascript">
$(document).ready(function() {
var s=1;
$('.add_select').click(function(e){ //Once add button is clicked
e.preventDefault();
s++;
$('.select_wrapper').append('<select class="form-control" name="txt-computer_sn['+s+']" id="txt-computer_sn_'+s+'">'+$('#txt-computer_sn_0').html()+'</select>');
});
});
</script>
there is 3 method to do this.i am not familiar with php.but i tell the method how to work it out.
1.you have to set an hidden field for count
2.
<select class="form-control" name="txt-computer_sn--" id="txt-computer_sn_--">
3.in the script write this var rep=/--/gi;
4. take your count from hidden field
var Count= $("#Count").val()
Count =++Count
("#div1").append($("#div2").html().replace(rep,Count));
on click the add button you have append the div2 with select to another
div1
on remove the
$("#div3"+id).remove()
in the order
<div1></div>
<div2 id="name1--"style=display:none>
<div3 id="name2--"></div3>
</div2>
it will work.use this concept .you can do this in php also..

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

how to send selected html row data to PHP backend script

I have a PHP form as below. Once user selects a particular row/rows I need to send the corresponding data to my PHP backend script. Here the externalID is unique. I face two issues in my code
Currently I get the entire form data to my PHP backend script,I need to data corresponding to only the rows I selected.
I have two buttons in the page and how can I call different php scripts on click of the button. Currently the click of "send MTDATA" calls the php script in form action.
src code:
<form target="iframe_b" action="/php_src/first.php" method="POST"
echo "sending data">
<fieldset>
<br><br>
<input type="button" id="activate_device" name="activatedevice" value="Activate_device">
<input type="submit" value="SEND MTDATA">
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>External ID</th>
<th>Status</th>
</tr>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'xxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ApplicationServer") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT EXTERNAL_ID,CONNECTION_STATUS FROM DEVICE_DETAILS") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$extID = $row['EXTERNAL_ID'];
$conStatus = $row['CONNECTION_STATUS'];
echo "</tr><tr>";
echo "</td><td>";
echo "<input type=\"checkbox\" class=\"case\" name=\"checkBox".$extID."\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classextID\" value=\"$extID\" name=\"textExID".$extID."\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classConnection\" value=\"$conStatus\" name=\"textcon".$extID."\" />";
}
?>
</table>
</fieldset>
</form>
output:
array(9) { ["checkBox123456#mydomain_com"]=> string(2) "on" ["textExID123456#mydomain_com"]=> string(19) "123456#mydomain.com" ["textcon123456#mydomain_com"]=> string(16) "request accepted" ["checkBox1234#mydomain_com"]=> string(2) "on" ["textExID1234#mydomain_com"]=> string(17) "1234#mydomain.com" ["textcon1234#mydomain_com"]=> string(16) "request accepted" ["checkBox53278#mydomain_com"]=> string(2) "on" ["textExID53278#mydomain_com"]=> string(18) "53278#mydomain.com" ["textcon53278#mydomain_com"]=> string(16) "request accepted" }
All html inputs - except unchecked checkboxes - are sent to the server so the only way to avoid that is to use javascript to remove the unselected rows from the form completely before the form is sent.
However, if the total amount of data is not the problem but you just want to be able to easily select the checked rows, you should use arrays in your html:
echo "<input type=\"checkbox\" class=\"case\" name=\"checkBox[".$extID."]\" />";
^ array ^
echo "</td><td>";
echo "<input type=\"text\" class=\"classextID\" value=\"$extID\" name=\"textExID[".$extID."]\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classConnection\" value=\"$conStatus\" name=\"textcon[".$extID.]"\" />";
Now your $_POST['checkBox'], etc. variables will be arrays in php as well so you can easily loop over them as the key is your $extID value. And as I mentioned before, only the checked checkboxes are sent to the server:
// Loop over the sent-in / selected checkboxes
foreach (array_keys($_POST['checkBox']) as $key) {
var_dump($_POST['textExID'][$key]);
// etc.
}
Also note that your html is probably not valid as you are not closing the last row but I don't think that would be causing any problems with the form.
One way is to collect the input in an array.
<?php
echo "</tr><tr>";
echo "</td><td>";
echo "<input type='checkbox' class='case' name='$extID[ checkBox ]' />";
echo "</td><td>";
echo "<input type='text' class='classextID' value='$extID' name='$extID[ textExID ]' />";
echo "</td><td>";
echo "<input type='text' class='classConnection' value='$conStatus' name='$extID[ textcon ]' />";
?>
Then if you check the $_POST you will find an array within an array, loop the first array and collect the details for each $extID.
As for the two buttons, you could name the submit button and then check to see which has been pressed.
<input type="button" id="activate_device" name="activatedevice" value="Activate_device">
<input type="submit" value="SEND MTDATA" name="submit_button">
<?php
if( isset( $_POST[ 'submit_button' ] ) )
{
// Process submit
}
elseif( isset( $_POST[ 'activatedevice' ] ) )
{
// Process device
}

jQuery validates input fields only in the first row of loop

This is my first post here so I apologize in advance if the formatting is wrong.
I am working on a form that pulls data from MySQL using a loop and outputs it to HTML page. The user then has the option to approve or deny the entries, and based on user selection validation should be required or optional. My current code will validate correctly, but only for the first row being outputted from the loop. I am trying to validate all rows. I have tried using a while loop and foreach statement with no success. Any help would be greatly appreciated!
My Loop & Form:
//connect to the database
$db=mysqli_connect('localhost','root','') or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysqli_select_db($db,"my_db") or die(mysql_error());
//-query the database table
$sql="SELECT id, date, client_name, client_number, date_completed, status FROM clients WHERE client_name LIKE '%" . $search ."%' OR status LIKE '%" . $search ."%' ";
//-run the query against the mysql query function
$result=mysqli_query($db, $sql);
//-count results
$rows=mysqli_num_rows($result);
if($rows=mysqli_num_rows($result)) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>" . $rows . " result(s) found for " . $search . "</h2><br />";
}elseif($rows=mysqli_num_rows($result) == 0) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>0 result(s) found for " . $search . "</h2><br />";
}
//-create while loop and loop through result set
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$date=$row['date'];
$client_name=$row['client_name'];
$client_number=$row['client_number'];
$date_completed=$row['date_completed'];
$status=$row['status'];
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed_returned' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
}
My jQuery code:
I am trying to make date_completed and upload fields required if user selects "Approved" under status field, and optional if he selects "Denied".
<script>
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#date_completed").prop('required',true)
}).trigger("change"); // notice this line
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#upload").prop('required',true)
}).trigger("change"); // notice this line
</script>
Thanks to KevinB I was able to find a solution to my problem.
I added class names for the input fields (status, date_completed, upload) I was trying to validate:
Updated code below:
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' class='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed' class='date_completed' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload' class='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
<script>
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.date_completed').prop('required',true)
}).trigger("change"); // notice this line
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.upload').prop('required',true)
}).trigger("change"); // notice this line
</script>

Categories