passing dynamic data to ajax request to retrieve mysql data - javascript

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>

Related

Multiple ajax returns and sum values

I have a group of dropdowns with a list of players. When a player is selected, their 'Value' should appear next to the drop down and the Total should update to be the sum of all selected players values.
php code below is for two players but I have ten, will likely have ten different similar functions for each of the dropdowns
select-player.php
<!--player1-->
<tr>
<td style="width:50%;">
<select name="player1" id="player1" onchange="showvalue1()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value1">
</td>
</tr>
<!--player2-->
<tr>
<td style="width:50%;">
<select name="player2" id="player2" onchange="showvalue2()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value2">
</td>
</tr>
<tr>
<th style="width:50%";>Total</th>
<th style="width:50%;" id="total"></th>
</tr>
ajax.js
function showvalue1(){
var x = document.getElementById("player1").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value1").html(data.price);
$("#total").html(data.newtotal);
}
})
}
function showvalue2(){
var x = document.getElementById("player2").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value2").html(data.price);
$("#total").html(data.newtotal);
}
})
}
I've read that jsonencode is used to send arrays back that I can then assign to IDs in js.
showvalue.php
<?php
include_once 'includes/dbh.inc.php';
$pl = $_POST['id'];
$pl = trim($pl);
$total = 0;
$total = $_POST['total'];
$sql = "SELECT value FROM players WHERE playername='{$pl}'";
$result = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_array($result)){
$newtotal = 0;
$value = $rows['value'];
$newtotal = $total + $value;
$ret = array('price'=>$value, 'newtotal'=>$newtotal);
echo json_encode($ret);
}
?>
Not getting any errors or console returns but also no values are being returned.
What am I missing?
Checking your HTML source, #total is a table cell:
<th id="total"></th>
And you are retrieving it using .value:
var t = document.getElementById("total").value;
But .value is for inputs, not text in a table cell, so that won't work.
To get the text, using jQuery instead of vanilla JS (since the rest of your code is jQuery):
var t = $('#total').text();

Updating rows of dynamic MySQL table using user input

UPDATE: for some reason the php file won't read the mysqli_query statment.
I have a dynamically filled table that has an input box to input a certain quantity amount in order to move a part to a different location with that quantity. Right now I am just trying to get the update code to work to update the current amount based on the inputted amount. Eventually I will add the ability to insert a new row into MySQL based on the inputted amount and inputted location.
It seems to be accessing the update.php file but have had no luck in the MySQL database being updated. I'm not sure how to send the data to the php file in order to update the appropriate rows.
This is my webpage:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<?php
if (isset($_GET['Placeid'])){
$moveplace = $_GET['Placeid'];
$sql = "SELECT *
FROM Parts p, Locations l
WHERE Placeid = '$moveplace' and p.locationid = l.locationid";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
<form onsubmit='updatetable()'
<table id='tablerun' class=searcht style='background-color:$bgcolor'>
<tbody>
<tr>
<td id='row1' value='".$row['id']."' name='moveid' style='display:none'>".$row['id']."</td>
<td value='".$row['PartNum']."' name='movepart'>".$row['PartNum']."</td>
<td value='".$row['ModelNum']."' name='movemodelnum'>".$row['ModelNum']."</td>
<td>".$row['Country']."</td>
<td>".$row['Region']."</td>
<td>".$row['Location']."</td>
<td>".$row['Placeid']."</td>
<td style='width:100px' value='".$row['UnitNum']."' name='moveunitnum'>".$row['UnitNum']."</td>
<td id='val' style='width:50px;' value='".$row['QTY']."' name='moveqty'>".$row['QTY']."</td>
<td value='0' type=text id='amt' name='moveamt'></td>
</tr>
</tbody>
</table>
</div>";
}
echo "<tr><td></td><td><input type='submit' class='submit' ></td></tr></form>";
}
}
?>
<script type="text/javascript">
function updatetable(){
$('#tablerun tr').each(function(){
var row_id = $(this).find("td:eq(1)").text();
var quantity = $(this).find("td:eq(8)").text();
var amt = $(this).find("input:eq(0)").val();
var data = {
id : row_id,
qty : quantity,
amt : amt
};
$.ajax({
type: "POST",
url: "update.php",
data: data,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
});
};
</script>
update.php:
<?php
include_once 'includes/database.inc.php';
$id = $_POST['moveid'];
$qty = $_POST['moveqty'];
$amt = $_POST['moveamt'];
$sql = "UPDATE parts set QTY = $qty - $amt where id = $id";
mysqli_query($conn, $sql) or die(mysqli_error($conn));
?>
P.S. I realize that I should be using prepared statements I plan on implementing them once I have completed this task.
Any help is appreciated

Call php function from Javascript inside php file

I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!

How to insert multiple rows in php with two data is not in the table?

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.

Pass the td value to php page using Javascript

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>

Categories