How to use the data from the row selected? - javascript

How can I collect the data on the row from the table that I select and use it in the result?
Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.
Here is the Javascript to select the row and call the data entry form
$(document).ready(function () {
$("tr").live('click',function(){
$.post('data_entry_form.php', function(data) {
$('#section2').html(data);
});
});
});
Here is the PHP Script
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>

The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.
//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";
//JS
$(document).ready(function () {
$("tr").live('click',function(){
//Get the ID from the row clicked
var id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
});
Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.
//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item
You would pre-populate your inputs like this
<input type="text" value="<?php echo $row['value']; ?>" />
or
echo '<input type="text" value="'.$row['value'].'" />';
NOTE: If your values contain quotes, you will want to replace them with the code "
echo '<input type="text" value="'.str_replace('"', '"', $row['value']).'" />';

Within the event handler, this and $(this) refer to your selected row:
$("tr").live('click',function(){
// this.cells[1] is the cell that contains Pubco Name
// You can also use $(this).children("td")[1]
...
});

Related

Passing a var in the same php page without refresh

I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});

Ajax: Data passing through button value not working

Problem: All the other portions of the program works. When I add data:$("#friendadd").val() it won't update the table. I believe the problem might be with the value form? I've seen others use it to get the value of textboxes but shouldn't it still work when using a submit button?
Purpose: each user on the website has an add-as-friend button next to it. When you click on that button, I want to put the userid of that user into a database "friends".
Javascript
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){//Used to be .each
$.ajax({
type:"POST",
url:"getuser.php",
data:$("#friendadd").val()
});//Add data: and success:function
//$.post('getuser.php');//JSON AJAX, {UserId:"13", FriendId:"16"}
})
});
</script>
PHP and HTML; $ctk_values are each of the users
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" value="<?php echo $ctk_values[$i][4];?>"><br>
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
getuser.php
<?php
if(!isset($_SESSION)){
session_start();
}
require "conn.php";
$gtu = $dbh->prepare("INSERT INTO friends (AskerId, AcceptorId, mutual, type) VALUES(:AskerId, :AcceptorId, :mutual, :type)");
$gtu->execute(array(
'AskerId'=>$_SESSION['UserId'],
'AcceptorId'=>$_POST['friendadd'],
'mutual'=>false,
'type'=>'friend'
));
?>

Getting text and sending it to a php function using javascript

I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>

No result in database when POST ID element in Javascript into PDO Insertion

I have this following code to handle selection in select form:
<script>
$(document).ready(function(){
$('#pilStock').change(function() {
var pilih_stock = $("#pilStock option:selected").text();
var hargaZ = $("#hargaX").text();
$.post("countme.php",{ hrg: hargaZ, dstock: pilih_stock},
function(data) {
document.getElementById("hasilhitung_pilihstock").innerHTML=data;
document.getElementById("jmlqty").innerHTML=pilih_stock;
}
);
});
});
</script>
Then I need to declare PHP variable, as:
$stock=isset($_POST['pilStock']);
$stock=strip_tags($stock);
After that, I need to save the data in $stock in the database but it gave me nothing.
This is the INSERT code I used:
$data = $xvg->prepare("INSERT INTO mytable (prod_stock) VALUES (:prod_stock)
$data->execute(array(':stock'=>$stock));
I tried it many times and makes me dizzy... please.
UPDATED:
Here's the SELECT OPTION which is related to $pilStock:
$stockz variable is from SELECT * FROM other_table (then the result must be selected by user and saved it in the database)
<?php
$stockz=$row['stock'];
if ($stockz=='1'){
echo "<select name='select' class='form-control' id='pilStock'>";
echo "<option value='1'>1</option>";
echo "</select>";
}
elseif ($stockz=='2'){
echo "<select name='select' class='form-control' id='pilStock'>";
echo "<option value='1'>1</option>";
echo "<option value='2'>2</option>";
echo "</select>";
}
?>
SELECT Script:
<?php
if ($stockz=='2'){
echo "<select name='select' class='form-control' id='pilStock'>";
echo "<option value='1'>1</option>";
echo "<option value='2'>2</option>";
echo "</select>";
}
?>
Previous:
$pilStock=$_POST['pilStock'];
Note: That didnot work because Javascript is being used by other PHP file in the same dir.
After:
$pilStock=$_POST['select'];
Note: This works when the name of the SELECT OPTION is called.
#JordanForeman.
--- please donot vote down if you feel this answer is crazy. just let me know how I should be. :p

checking dynamically created textboxes for values

I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };

Categories

Resources