Mysql result not show inside div (only table header) - php

I try to show Mysql result as table inside <div> after click submit button, but it just only show <table></table>. No problem found during posting value to process page.
So far, my script is like:
<form id="myform">
....................
<button id="input" type="button" class="ui-state-default ui-corner-all"><span>Submit </span></button>
<input name="action" value="openreport" type="hidden">
</form>
<div id="show"></div>
$("#submit").click(function(){
var params=$("#myform").serialize();
$.ajax({
type:"post",
url:"go.php",
data:params,
cache :false,
async :false,
success : function(result) {
$('#show').replaceWith(result);
}
});
});
page go.php:
<?php
//CONNECT TO DATABASE
$dbc=mysql_connect(_SRV, _ACCID, _PWD) or die(_ERROR15.": ".mysql_error());
mysql_select_db("qdbase") or die(_ERROR17.": ".mysql_error());
switch (postVar('action')) {
case 'openreport':
openreport(postVar('model'),postVar('line'),postVar('lot_no'));
break;
}
function openreport($model,$line,$lot_no){
$Model = mysql_real_escape_string($model);
$Line = mysql_real_escape_string($line);
$Lot = mysql_real_escape_string($lot_no);
$group=" GROUP BY DATE ";
$sql="SELECT Range_sampling,DATE(Inspection_datetime) AS DATE FROM
inspection_report WHERE Model LIKE '".$Model."'";
$sql.="AND Line LIKE '".$Line."' AND Lot_no LIKE '".$Lot."'".$group;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo("<tr><td>$row[0]</td><td>$row[1]</td></tr>");
// echo "<tr>";
// echo "<td>" . $row['Range_sampling'] . "</td>";
// echo "<td>" . $row['DATE'] . "</td>";
// echo "</tr>";
}
echo "</table>";
mysql_close($dbc);
}
?>
I have no idea because I'm not really understand how to show mysql result as a html table.

The AJAX call is made only if a button is clicked that has an id of “submit”; however, your submit button has an id of “input”. Try changing the line that reads:
$("#submit").click(function(){
to
$("#input").click(function(){
As Yun suggested, to keep <div id="show">...</div> wrapped around the table, change
$('#show').replaceWith(result);
with
$('#show').html(result);
I don’t know if this will help or not, but it’s the only thing that stands out to me.

Try
$('#show').html(result);
instead of replaceWith to preserve the div

you can simply load the results of your php page into div
$('div#show').load('go.php',params,function() {alert('Loaded!'); });
Just make sure that you replace POST with REQUEST in your php file.
The POST method is used if data is provided as an object; otherwise, GET is assumed.

Related

Differentiate between multiple buttons on a table. html php

I am creating an edit edit/delete user table and have created an 'edit' button for each record populated in the table. I want to do several things.
1. when an edit button is pressed for a specific user, open a new page called "EDIT."
2. populate form controls in the "EDIT" page with the corresponding user information for the specific 'edit' button that was pressed.
My question is, how do I differentiate between which button is pressed on the users table?
this is what my table looks like:
And this is the code for generating the table and buttons.
if (!$_REQUEST['search']) {
$sql = "SELECT * FROM users_table ORDER BY lname ASC";
$retvalues = mysqli_query($conn, $sql);
$counter = 1;
while ($row = mysqli_fetch_array($retvalues, MYSQL_ASSOC)) {
$lname = capword($row['lname']);
$fname = capword($row['fname']);
if ($row['admin'] != 1) {
$stringAdmin = "No";
$admincolor = "<td>";
} else {
$stringAdmin = "Yes";
$admincolor = "<td style='color:red;'>";
}
echo "<tr>";
echo "<td>".$counter.".</td>";
echo "<td>".$lname." , ".$fname."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['password']."</td>";
echo $admincolor.$stringAdmin."</td>";
echo "<td><input type='checkbox' name='user[]' value='{$row['id']}'></td>";
echo "<td><input type='submit' name='edit' value='edit'></td>";
echo "</tr>";
$counter++;
}
}
You can differentiate the each edit button by using unique id
<button class='edit' data-id="<?php echo $_GET["id"];?>"> EDIT</button>.
While click on the edit button, read the data-id by using the following code
$(document).on('click', '.edit', function(){
var id = $(this).attr('data-id');
//code - you need to do
})
Better to show the data on next page, use bootstrap model box and AJAX request which will interact lot of the users.
$(document).on('click', '.edit', function(){
var id = $(this).attr('data-id');
if(id) {
$.ajax({
url : your url("profile/edit/"+id)
type : 'post',
success: function(response){
if (response.success) {
$('#modal').modal('show');
}
}
}):
}
});
If you change the value attribute of "Edit" submit button to the row id you can use this value to know what record id will be edited and populate it.
"<input type='submit' name='edit' value='edit'>"
change to
"<button name='edit' value='{$row['id']}'>Edit</button>"
Note that if the whole table is the form container, all inputs in table will be posted, not only the current row.
I would make the edit button into a hyperlink instead. Then there's no need to have form code. I'm assuming you don't need to pass the "delete" parameter to your edit page (as that's a different operation).
Instead of
echo "<td><input type='submit' name='edit' value='edit'></td>";
write
echo "<td><a href='edit.php?id=".$row['id']."'>Edit</a></td>";
Then in edit.php look for the variable
$_GET["id"]
and use that to search the database and display the appropriate record for editing.
P.S. If you still want your "Edit" hyperlink to look like a button it's quite easy to do that with CSS.
I did this by creating and calling a javaScript function that passes the id of the row as an argument.
echo"<tr>";
echo"<td>".$counter. ".</td>";
echo"<td>".$lname. " , " .$fname."</td>";
echo"<td>".$row['email']."</td>";
echo"<td>".$row['password']."</td>";
echo $admincolor . $stringAdmin ."</td>";
echo"<td><input type='checkbox' name='user[]' value='{$row['id']}'></td>";
echo"<td><input type='button' name='edit' value='edit' onclick='javascript:editUser(". $row['id'].");'></td>";
echo"</tr>";
the function redirects the user to an 'edit' page while passing the value of the id in the url.
function editUser(id){
window.location = "edituser.php?id="+id;
}
once on the edit page, i used $_GET to retrieve the id value and edit my entry.
You can change and add a form to your table like this:
echo "<tr>";
echo "<td>".$counter.".</td>";
echo "<td>".$lname." , ".$fname."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['password']."</td>";
echo $admincolor.$stringAdmin."</td>";
<form action="edit.php" method="post">
echo "<input type="text" name="id" value="$row['id']" style="visibilty: hidden;">";
echo "<td><input type="checkbox" name="delete"></td>";
echo "<td><input type="submit" name="edit" value="edit"></td>";
</form>
echo "</tr>"
First we have defined a form with POST method: <form action="edit.php" method="post"> and let's say edit.php will handle the request.
Then we have added a hidden form element to store and pass the user's ID: <input type="text" name="id" value="$row['id']" style="visibilty: hidden;"> It was possible to use value="..." of "edit" button but if you are dealing with passing more than one variables with POST or GET method, the trick is using an extra form element with visibility: hidden; CSS property.
Eventually, it will pass the value of $row['id'] to edit.php when the form has been submitted.
and we can handle the request in edit.php like this:
<html>
<body>
User with this ID number: <?php echo $_POST["id"]; ?> will be edited.
</body>
</html>
Official guide: http://php.net/manual/en/tutorial.forms.php
You can either use POST or GET method to pass the variables. For a detailed comparison: https://stackoverflow.com/a/504993/2104879

Saving a specific row using PHP and a search option

I have the following program, it searchs for the text placed in a previous php file, and it displays the results, by adding a radiobox to check the item that will be purchased. I am not able to make the page save the item that was checked from the items found into a new table, I don't know how to do that, because the items found are placed as fetched items, therefore I don't know how to select one to save the entire row selected. Please help!.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Search option</title>
</head>
<body>
<?php
echo "<form action='slips.php' method='post'>";
if(isset($_POST['name_prod2'])){
$word=$_POST['name_prod2'];
$conn = oci_pconnect('dbname', 'password', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['Error'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM product WHERE LOWER(name) LIKE '%" . $word . "%'");
oci_execute($stid);
echo "<table width='950' table border='1' align='center'>\n";
echo "<tr>\n";
echo "<th width='50'> <div align='center'>buy</div></th>";
echo "<th width='110'> <div align='center'>Product ID</div></th>";
echo "<th width='190'> <div align='center'>Product name</div></th>";
echo "<th width='250'> <div align='center'>Description</div></th>";
echo "<th width='100'> <div align='center'>in Store</div></th>";
echo "<th width='100'> <div align='center'>price</div></th>";
echo "<th width='190'> <div align='center'>Quantity to purchase</div></th>";
echo "</tr>\n";
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
//echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>', $product['product_id']);
foreach ($product as $aspect) {
echo '<td><div style="text-align:center">'.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>';
}
echo "</table>\n";
}
echo "<div style='text-align:center'><input type='submit' value='Comprar'></div>";
echo"</form>";
?>
</body>
</html>
These are two of the Javascripts that I have tried so far to complete this, but they fail to tell me when one has been selected, I don't know if I can try adding this code to a button, and when I click it, it will tell me which row from the radio box was checked, and then save it:
<script type="text/javascript" src="js/jquery.js"> </script>
<script type="text/javascript">
var user_cat = $("input[radio1='user_cat']:checked").val();
if (!$("input[radio1='radio1']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
$(document).ready(function() {
$('#btnStatus').click(function(){
var isChecked = $('#rdSelect').prop('checked');
alert(isChecked);
});
});
</script>
When is use this line echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>"; it works and displays this results
But when I use this line echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%d"></label></td></div>', $product['product_id']);it doesn't work and displays this results
OK, picking up the information from the comments to the question and doing a little guess work I will try to point you into the right direction. It is not possible to give a read-to-use answer, since still there are things not clear, but let's have a try to get started...
I see you have an html form which includes a table. That table has a header row and dynamic generated rows holding some product information each. You want to have a radio button in front of each row to allow to select a row. And you want a text input field at the end of each row which allows to enter a quantity. Then you want to post that information to the server to be able to process it.
I will stick with the "conservative" html approach and not introduce scripting here. Reason is that for the purpose described before that is not required. So let's keep things simple. Obviously nothing speaks against making things more complicated later on :-)
Your radio buttons have to be changed, they currently make no sense. You have to give the an individual value, so that you can identify which row has been selected later on. Currently you give them all the same static value 'value'. So change the loop that iterates over the products to something like:
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>'."\n", $product['product_id']);
foreach ($row as $aspect) {
echo '<td><div style="text-align:center">'
.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')
."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>'."\n";
}
Note: I took the liberty to change the chosen names to be more logical to product, aspect and quantity...
That is all... Now when you press the submit button the form should get posted to the target you specified: slips.php which is probably a script of yours... Inside that script you now can access the data like that:
$product = $_POST['product'];
$quantity = $_POST['quantity'];
There are more issue worth discussing and modifying, but as said: let's keep things simple and take one step after the other!
ChangeLog:
changed the literal key of the array element used as a value inside the radio button definition from id to procduct_id according to one of the comments below
Your radiobox need to stay inside the form.

How do I make it so that when I edit a cell on this page, it saves it to the database's table?

This page generates a table that contains all
the data on the billing_reports table in my database. When you double
click on an item, you can enter in a new value in the field, then press
enter to save. The problem is that when I press submit, it
just refreshes the page, without updating the changes to the database.
How do I fix this?
<?php
include_once ("includes/config.php");
include_once ("includes/functions.php");
include_once ("includes/header.php");
?>
<!--How this works, is that this page generates a table that containes all
the data on the billing_reports table in my database. When you double
click on an item, you can enter in a new value in the field, then press
enter to save. The problem I am having, is that when I press submit it
just refreshes the page, when I want it to update the changes to the database.
How do I fix this? -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<?php
// $data = All the rows in billing reports
$data = mysql_query("SELECT * FROM billing_reports")
or die(mysql_error());
// This is printing the Javascript table listed above
?> <table class="editableTable"> <?php
Print "<editableTable border cellpadding=4>";
//This is defining $info as the action that seperates the $data pulled from the database
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['cc_name'] . "</td> ";
Print "<th>ID:</th> <td>".$info['br_id'] . "</td> ";
Print "<th>Listing ID:</th> <td>".$info['listing_id'] . "</td> ";
Print "<th>Payment:</th> <td>".$info['billing_amount'] . "</td> ";
Print "<th>Status:</th> <td>".$info['status'] . " </td></tr>";
}
Print "</table>";
if (!$_POST['submit']) {
$result = mysql_query($info);
$person = mysql_fetch_array($result);
}
if(isset($_POST['submit'])) {
$info = "UPDATE billing_reports SET cc_name='$_POST[cc_name]', br_id='$_POST[br_id]', listing_id='$_POST[listing_id]', billing_amount='$_POST[billing_amount]', status='$_POST[status]'";
mysql_query($info) or die(mysql_error());
echo"Agent has been modified!";
}
?>
<form action="" method="post" class="button">
<li>Save Changes</br>
<input type="submit" <name="submit" value="Modify"/></li>
</form>
<?php
include_once ("includes/footer.php");
?>
You have a misstaping in your input which is making the input itself not workig, isset() for submit will never be true
<input type="submit" <name="submit" value="Modify"/></li>
//^ here you don't need <
As side not i would advise that you are highly vulnerable to mysql injections, i would rather switch either to pdo or mysqli and use prepared statements
There's a typo in this line, < before name:
<input type="submit" <name="submit" value="Modify"/></li>
And using an editor with code highlighting is usually recommended.

sending checked box values to php script to process via jquery

I have a table with four columns with a checkbox at the end of each row. I would like to know if there is a way of writing a jquery function that will select all the values of each row when the check box has been ticked and the submit button has been clicked.. and then pass the values to .php file to process/display. The reason i want to use the .php file is because i want to run a query to show all registered users on my system and then send the checked rows (id and name) to those users.
Sounds very complicated but i really need some help. thanks in advance.
here is the html code:
<div class="valuesOfObs">
<table>
<thead><tr><th>Valuation Name</th><th>Valuation Goal</th><th>Valuation Description</th><th>Options</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM valuation';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ValuationID'].'">';
echo '<td class="crsDesc">'.$row['ValuationName'].'</td>
<td >'.$row['ValuationGoal'].'</td>
<td >'.$row['ValuationDescription'].'</td>
<td ><a href =values.php?action=invite&id=aValue> xValue </a></td>
<td > <input type="checkbox" name="selectValue">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
<input type="button" name="addrow" id="addrow" value="Add row">
<input type="button" name="inviteObs" id="inviteObs" value="Invite Obstacle";>
Here is what I have written for the jquery so far.. I am trying to spilt the values so i can choose specifically which ones to process and then later on user the .join() method. Please help out if on the wrong track
$("input[type=checkbox], input[type=button]").on("click", function () {
$( ":checked" ).map(function() {
return $(this).closest("tr").text();
}).split("</td><td>");
var compName = $("#id").val();
$.ajax({
url : "inviteObstacles.php",
type : "POST",
data : {"compID" : compName},
success : function (n){
//do something
}
})
});
Use .map() function to pass each element in the current matched set through a function, which will produce new jQuery object containing the return values.
Here is a code:
$("input[type=checkbox]").on("click", function () {
$( ":checked" ).map(function() { return $(this).closest("tr").text();
}).get().join(); //Use join to split the fetched row using separator "," on server-side
});
Demo: http://jsfiddle.net/tSeau/1/

AJAX return, update table on page

I have the following that is generate for every record in my database
$allbills = mysql_query("SELECT * FROM outgoings WHERE outgoings.user_id = '$uid'") or die(mysql_error());
echo "<table>";
while($info = mysql_fetch_array( $allbills ))
{
echo "<tr>";
echo "<th>bill id:</th> <td>".$info['id'] . "</td> ";
echo "<th>total:</th> <td>".$info['bill'] . "</td> ";
echo "<th>bill name:</th> <td>".$info['bill_name'] . "</td> ";
echo "<th>bill deposit:</th> <td>".$info['bill_description'] . "</td> ";
echo "<th>colour:</th> <td>".$info['bill_colour'] . " </td>";
echo "<th>edit:</th> <td>
<form class='bill-upd'>
<input type='hidden' value='".$info['rand']."' name='rand2' id='rand2'>
<input type='hidden' value='".$info['id']."' name='billid' id='billid'>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' class='bill-upd-submit' />
</form>
</td>";
echo "</tr>";
}
echo "</table>";
This updates my users record in a table using AJAX
$(document).ready(function(){
$(".bill-upd-submit").click(function() {
var elem = $(this);
$.post('update_bill.php', elem.parent('.bill-upd').serialize(), function(data) {
elem.append(data);
});
});
});
Once this is done however, the user needs to refresh the page to see the results, is there a way I can populate the table the user edits, with the latest data after the update query takes place?
I would try a different approach:
1) Add an invisible div right after your button. You can do this dynamically:
$(document).ready(function() {
$(".bill-upd-submit").after("<div style='display:none'></div>");
// ...
});
2) Now your post event would be as follows:
$(".bill-upd-submit").click(function() {
var elem = $(this);
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data) {
elem.next("div").html(data);
});
});
BTW, I'm assuming that there are other buttons in the same page, and that's the reason for using class (bill-upd-submit) instead of id. If there is just one button, id is faster. Also, I think that bill-upd-submit is of type button. If it is type submit, I would change-it to button or added the following to the click event:
function() {
// ... the code shown above
return false;
});
This will prevent the form's submit to happen.
Looks to me like your current javascript is trying to append the form, not the table. If you're trying to add a row to the table at the bottom and keep all the other rows, then this might work. Give your table an ID in the html markup (here I use "table_id"):
$(".bill-upd-submit").click(function() {
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data){
$("#table_id tr:last").after(data);
});
});
And just make sure your php file (update_bill.php) has the appropriate html built into it to echo a proper tr for you.

Categories