I have a HTML table the displays record from database.
Below is a screenshot of my table
There is a button in a TD (i.e column 5,7,9), when I click the button I want to perform function to display a popup box with html table.
Before that I want to pass the value of mcc and mnc and also want to pass the column name (i.e if i clicked the button near 5xx i want pass 5xx if 6xx I want to pass 6xx) to the page where there is a query to display the table. And have separate php code to retrieve th and td from database.
I tried but I don't know how to pass this value to javascript then to php page that contains query to display the table. Thanks
This is my HTML markup:
<table>
<th style="text-align:center;width:92px">MCC</th>
<th style="text-align:center;width:92px">MNC</th>
<th style="text-align:center;width:92px">MNP</th>
<?
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i = 0;
while($rows = mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows[0];
echo "<th>" . $columnArray[$i] . " <span> <img id='logo' src='/image/Picture2.png' style='margin:-62px -21px -9px 32px'></span></th>";
echo "<th style= 'width:20px;'></th>";
$i++;
}
?>
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
} ?>
</table>
Javascript
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "testpage2/config.php";
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
but it not passing the value of mcc and mnc also the column
First of all assign Id to table:
<table>
like:
<table id="contentTable">
Now use below code of jQuery:
$(document).ready(function ()
{
$('#tableId').find('th').each(function ()
{
$(this).click(function ()
{
var thValue = $(this).html();
alert(thValue) // here is value of th on you have click
});
});
});
Cheers!!!
You could try to use something like "generic javascript":
<?php //some stuff
$mcc = "some value";
?>
<script type="text/javascript">
var myVariable = <?php echo $mss; ?>
</script>
Related
I have a data from mysql database. I these data comes with a individual unique ids in a table format, when i click on a particular table row, i want to post that id via ajax and append the result in a div.
code for search and retrieving data from mysql
<?php
require ('config/searchConfig.php');
$return = '';
if(isset($_POST["query"]) && !empty($_POST['query']))
{
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query = "SELECT * FROM products WHERE productName LIKE '%".$search."%' ORDER BY ID DESC " ;
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
$return .='
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th>Product Name</th>
<th>Price</th>
</tr>';
while($row1 = mysqli_fetch_array($result))
{
$return .= '
<tr id="add-btn" style="height:5em;" >
<td id="getID" value='.$row1["ID"].'>'.$row1["ID"].'</td>
<td id="productName" value='.$row1["productName"].'>'.$row1["productName"].'</td>
<td id="price" value='.$row1["price"].'>GHC '.$row1["price"].'.00</td>
</tr>
';
}
'</table></div>';
echo $return;
}
else{
echo 'No product Found with that Name';
}
}
?>
code for appending the result in a div when you click on the table row.
<script type="text/javascript">
$(document).on('click', '#add-btn', function() {
var getID = $('#getID').attr('value');
$.ajax({ //create an ajax request to display.php
url:"getPrice.php",
method:"GET",
data:{getID:getID},
success: function(data){
$("#dynamicAddRemove").append(data);
}
});
});
</script>
I have a problem inserting the multiple row from my table to my database. Ill show picture of my UI.
https://i.stack.imgur.com/1okJB.png
There are 5 column that I will insert into my database Barcode,Description and QTY is in the table that I want to insert and the two data is outside the table,or not on the table e.g username and customer_id. Its printed on the other part of my UI.
I tried this ajax code but nothing happen.
$(document).on('click','.Enter',function(e){
var user = [];
var product = [];
var customer = [];
var quantity = [];
$('input .user').each(function(){
user.push($(this).text());
});
$('tableData tr td .barcode').each(function(){
product.push($(this).text());
});
$('select .customer_id').each(function(){
customer.push($(this).text());
});
$('tableData tr td .qty').each(function(){
quantity.push($(this).text());
});
$.ajax({
url:"insert_sales.php",
method:"POST",
data:{user:user, product:product, customer:customer, quantity:quantity},
success: function(data){
alert(user[0]);
},
})
});
This is part of my HTML file.
<input type="hidden" name="user" value="<?php echo $row['username']; ?>" class="user" />
<select class="customer_id" name="customer" style='cursor:pointer'>
<?php
if(mysqli_num_rows($show)>0){
while ($row = mysqli_fetch_array($show)) {
?>
<option value="<?php echo $row['customer_id']; ?>"><?php echo $row['firstname'];?>
</option>
<table id="table2">
<thead>
<tr class='text-center'>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
This is my insert_product.php file.
if(isset($_POST['user'])){
$user = $_POST['user'];
$product = $_POST['products'];
$customer = $_POST['customer'];
$quantity = $_POST['quantity'];
$query = '';
for($count = 0; $count<count($user); $count++){
$user_clean = mysqli_real_escape_string($db, $user[$count]);
$product_clean = mysqli_real_escape_string($db, $user[$count]);
$customer_clean = mysqli_real_escape_string($db, $user[$count]);
$quantity_clean = mysqli_real_escape_string($db, $user[$count]);
if($user_clean != '' && $product_clean != '' && $customer_clean != '' && $quantity!= ''){
$query = "INSERT INTO sales(username,product_id,customer_id,quantity) VALUES('$user_clean',$product_clean,$customer_clean,$quantity_clean)";
}
}
if ($query != ''){
if(mysqli_multi_query($db,$query)){
echo "Item Inserted"
}else{
echo "Error";
}
}else{
echo "No Product";
}
}
Hope someone can help me about this one. I'd put an alert in ajax to know if the it passes to the code. There's no insert happening even though it passes to the alert.
I'm trying to delete data from database but when I click on delete button then its delete the first row not where I'm clicking.
my PHP Code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
And this is my ajax code:
function deleteproduct(){
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("alerts").innerHTML = http.responseText;
}
}
var delid = document.getElementById("productid").value;
var file = "assets/php/addproduct_deletedata.php";
var senddata = "productid="+delid;
http.open("POST",file,true);
http.setRequestHeader("content-type","application/x-www-form-urlencoded");
http.send(senddata);
}
I want that when I click on delete button then it delete the row where I clicked not others.
FIRST OF ALL YOU CANNOT ASSIGN THE SAME ID TO MORE THAN ONE ELEMENTS ON A PAGE.
The browser won't mind it but It makes the HTML invalid. You can use class attribute for this purpose.
You can validate your HTML online here
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
For your requirement, you can use anchor tag instead of using a form with a hidden input field to reduce the DOM size and call the function on click and pass the function the productId as a parameter.
Here's the code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr id='row-".$rows["id"]."'>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><a href='#' onclick='return deleteproduct(".$rows["id"].")'>Delete</a></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
JavaScript:
function deleteproduct( delId ){
var tableRowId = 'row-'+delId;
// you got delId and tableRowId to remove the table row
// do ajax stuff here...
return false;
}
Let me know how it went.
because its "value" and not "vlaue" ;)
input type='hidden' id='productid' vlaue='".$rows["id"]."'
2.
you're iterating over your resultset and printing out an input-field with the id "productid".
In your code, EVERY column has the SAME id. Thats the reason your javascript isn't working as expected. An ID needs to be unique.
You need to send the value (product id) as the function parameters. Do it like this:
<input type="hidden" onclick="deleteproduct(this.value)" value="$yourRowId"/>
or
<input type="hidden" onclick="deleteproduct($yourRowId)" />
and this is how you can retrieve the value in JS:
<script type="text/javascript">
function deleteproduct(id)
{
alert(id); // your product ID
}
</script>
I have a table in an oracle database that I am showing on a web page. I used bootstrap to style my page and dataTables for pagination and search as well as sorting. I want to update any particular row at anytime using the unique ID column(BID), so I have added an update link next to each row using the foreach loop.
My problem now is to get the logic to build that functionality to make the update link. I want to:
Find a way to know which row the user has clicked to update, and retrieve that record/row to a form for update using the ID.
Challenge:
I am using a loop to fill the table and I can't think of a way to link each row ID to the update link by it. I tried filling an array with the ID's but how to connect what update link to what ID for retrieval beats me.
I am using html and PHP as well as some simple javascript. I am not good at javascript and have little knowledge in ajax also. I am yet to learn them but I understand they are the best to use for such things. Perhaps, I am not using the best approach, so if anybody can help me out with a much better one within my scope. Find my code below.
<table class="table table-striped" id="scriptstable">
<thead>
<tr>
<th>Update</th><!--This is where update links are-->
<th>Place</th>
<th>Report Name</th>
<th>Index</th>
<th>Source</th>
<th>Core Field</th>
<th>Description</th>
<th>ID</th>
</tr>
</thead>
<?php
//Connection string is here
$stid = oci_parse($conn, 'SELECT * FROM mytable ORDER BY REPORT_NAME');
oci_execute($stid);
echo "<tbody>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr>";
echo " <td><a data-toggle='modal' data-target='#myModal' href='#' >Update</a>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
} $bid[]=$row['BID'];//Array that stores ID as they come
echo "</tr>";
}
?>
</tbody>
</table>
UPDATE:
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
//Connection
$conn = oci_connect('username', 'password', 'localhost/XE', 'WE8MSWIN1252');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM Bo_repository WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
// echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
echo " <td><a id='{$row['BID']}' href='#' onclick='updateRow(this)'>Update</a></td>";
//header("Location:index.php");
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
?>
When you emit your rows in the table you can assign the id to the table row... I usually do it concat with row or something... and include the id as the id of your tag. You can then use the onclick to call a javascript function using ajax to update your table row dynamically e.g.
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr id='row_{$row['BID']}'>";
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
$bid[]=$row['BID'];//not sure this is really needed anymore
echo "</tr>";
}
The updateRow function would be something like this... In a script tag of course...
function updateRow(element) {
var id = jQuery(element).prop('id');
var url = 'your_back_end.php_file_that_handles_Ajax';//e.g. AjaxHandler.php
var postArg = {};
postArg['BID'] = id;
postArg['ajaxaction'] = 'updateRow';
jQuery.ajax({
url: url,
type: "post",
data: postArg,
success: function (response) {
jQuery('#row_' + id).html(response);
},
error: function(response){
console.log(response);
}
});
}
Your backend file would be pretty simple... I create a class called AjaxHandler and pass all ajax calls to the class for whatever processing I need to do...
Your file could be something like this example...
AjaxHandler.php
<?
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM mytable WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
This is a very basic async dynamic update using php and ajax...
Hope this helps...
I am trying to pass the the td value to java script,from java script i post that value to the php page where it contains query.can any one guide me how to pass the td value to java script,i tried but i don't know how to pass this value .thanks
Below is my js code :
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var url = "testpage2/config.php";
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
Html
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
}
?>
value is for input elements. For others(like td, th, div, span...) use innerHTML:
var mcc = document.getElementById("mcc").innerHTML;
var mnc = document.getElementById("mnc").innerHTML;