How to get value of dynamically generated table using javascript - javascript

here i am trying to get the value that is inside <td> value </td> using javascript getElementById(ID); but i am not able to fetch the value and display value in alert box.
code:
<script type="text/javascript">
function getvalue()
{
var lat = document.getElementById('lat').value;
var lon = document.getElementById('lon').value;
var lati = parseInt(lat);
var long = parseInt(lon);
alert(lati,long);
}
</script>
php-html code:
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['theater_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td id='lat'>" . $row['lat'] . "</td>";
echo "<td id='lon'>" . $row['lon'] . "</td>";
echo "</tr>";
}
The table is auto generated by php from database table values for only one record. now i want to fetch lat and lon value in javascript and alert it.. but now i am not able to get alert...How can i do this?

var lat = document.getElementById('lat').innerHTML;
var lon = document.getElementById('lon').innerHTML;
value is for <form>s elements(<input>, <select> etc').

Related

Not able to store ajax variables in session array

I am making a cart-mechanism with jquery, ajax and php. The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:
$(document).ready(function(){
$("#cart").on("click", function(){
var name = $("#name").text();
var cost = $("#cost").text();
$.ajax({
type:"post",
data:"name="+name+"&cost="+cost,
url:"senddata.php",
success:function(data){
$("#info").html(data);
}
});
});
});
This is my html displayed with php:
function getData()
{
require_once('../config.php');
$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");
while($row = mysqli_fetch_assoc($query))
{
echo "<form><tr>";
echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
echo "<td>" . $row['p_pic'] . "</td>";
echo "<td>" . $row['p_desc'] . "</td>";
echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}
mysqli_close($conn);
}
And finally, this is where I have stored the ajax variables in a session array:
session_start();
$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);
$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);
I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.
Variables does not appended because you initialize every time the
$_SESSION['cart_name'] = array();
$_SESSION['cart_cost'] = array();
That means that every time before you push the new data you empty the SESSION var.

Passing Parameters To PHP Table Hyperlink

I want the second and third columns of my php table to be a hyperlink to a different page for each row. I need to pass 3 parameters to the hyperlink
1) The value from the first column - empID listed in the table below
2) The value from $weekStart - selected from a input type="date" at top of page
3) The value from $weekEnd - selected from a input type="date" at top of page
I am trying this syntax, but it is not passing in the parameters and I am getting a page not found error. How should this syntax be altered so that it passes all 3 params and navigates to the appropriate page?
Week Start:<input type="date" name="weekStart">
Week End:<input type="date" name="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
?>
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td>'.$Row['DailySales'].''" . $res->DailySales . "</td>";
print "<td>'.$Row['SalesForWeek'].''" . $res->SalesForWeek . "</td>";
print "</tr>";
}
You didn't append the string well. Please try the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['SalesForWeek']."</a>" . $res->SalesForWeek . "</td>";
print "</tr>";
}
If it still shows not found page, then please check the file names.
Update: I hope you need to replace some variables in your loop as updated in the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->SalesForWeek."</a></td>";
print "</tr>";
}
Completely untested and I'm not 100% sure what the data in those links were supposed to be doing, but I think this should give you a solid starting point and you can tweak the HTML generation to get what you want.
I wouldn't bother trying to do it in PHP at all, pass the entire data set to JS and do it there.
Week Start:<input type="date" name="weekStart" id="weekStart">
Week End:<input type="date" name="weekEnd" id="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
// Create a JSON version of your data to pass to the script
$data = json_encode( $tsql );
?>
<!-- Create an empty table for your data-->
<table id="employee-table"></table>
<script>
$("#submitForm").on("click", function(e) {
// Stop the form from reloading the page
e.preventDefault();
// Set up your variables, you'll need to add ID's to the form inputs
var employees = <?php echo $data; ?>;
// See the employees data in your inspector console
console.log(employees);
var weekStart = $("#weekStart").val();
var weekEnd = $("#weekEnd").val();
// Generate the HTML for all the employees
var html = "";
for( var1=0; i<employees.length; i++ ) {
html += "<tr>";
html += "<td>" . employees[i].EmpID . "</td>";
html += "<td>" + employees[i].DailySales + "</td>";
html += "<td><a href='WeeklySales.php?param1='" + weekStart + "'&param2='" + weekEnd + "'&param3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>

Why doesn't 'onclick' work when html is sent through php?

There is a javascript in my page that loads a PHP script into a div every second. This PHP is supposed to run a SQL query that loads data from a database.
Here is an extract of the PHP
while($row = mysqli_fetch_array($result))
{
$starttime = $row['start_time'];
$module = $row['module'];
$item = $row['item'];
echo "<tr>";
echo "<td>" . $row['start_time'] . "</td>";
echo "<td>" . $row['module'] . "</td>";
echo "<td>" . $row['item'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['accepted'] . "</td>";
echo "<td>" . $row['end_time'] . "</td>";
echo "<td><button id='btnaccept' onclick='acceptBtn()'>ACCEPT</button></td>";
echo "</tr>";
}
And here is the Javascript
<script>
var auto_refresh = setInterval(
(function () {
$("#dataDisplay").load("updatedb.php"); //Load the content into the div
}), 1000);
</script>
As you can see, the last table data is a button that runs a Javascript function
<script>
function acceptBtn() {
window.alert("Accepted");
}
</script>
But unfortunately, clicking this button won't run the function. Any help would be appreciated
Try set listener:
echo "<td><button id='btnaccept'>ACCEPT</button></td>";
.
$(document).on('click', '#btnaccept', acceptBtn);
function acceptBtn(event) {
event.preventDefault();
window.alert("Accepted");
}

Sanitize strings to avoid special characters break javascript generated by php

I have a php 'search' script that looks for the requested data in a MySQL database and prints a table. Each row of this table can be modified or deleted by clicking on an icon. When you click on one of these icons a javascript function that shows a display is called.
This is the piece of code:
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Sanitize output
$user = htmlentities($row[0]);
$name = htmlentities($row[1]);
$surnames = htmlentities($row[2]);
$email = htmlentities($row[3]);
$role = htmlentities($row[4]);
$access = htmlentities($row[5]);
$center = htmlentities($row[6]);
$message .= "<tr>
<td>" . $user . "</td>" .
"<td>" . $name . "</td>" .
"<td>" . $surnames . "</td>" .
"<td>" . $email . "</td>" .
"<td>" . $role . "</td>" .
"<td>" . $access . "</td>" .
"<td>" . $center . "</td>" .
"<td>" .
"<input type='image' src='../resources/edit.png' id='edit_" . $user . "' class='edit' onclick=edit_user(\"$user\",\"$name\",\"$surnames\",'$email','$role','$access',\"$center\",'$id') title='Editar'></button>" .
"</td>" .
"<td>" .
"<input type='image' src='../resources/delete.png' id='delete_" . $user . "' class='delete' onclick=delete_user(\"$user\",'$role') title='Eliminar'></button>" .
"</td>
</tr>";
}
This is just part of the table I generate. After all this, I encode the table with json_encode and echo it. The echo is captured by an ajax function that decodes it (JSON.parse) and puts it into a div.
The table is correctly rendered and everything works fine with normal characters, but I have detected I can have some problems if I have quotes, slashes and another meaningfull characters. The strings are showed correctly in the table, so there is no problem with php, but the generated javascript doesn't work with some strings.
For example, if I introduce:
</b>5'"
or:
<b>5'6"</b><br><div
as users, when I click on edit or delete icon I get some errors in javascript console:
Uncaught SyntaxError: Invalid regular expression: missing /
home.php:1 Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: Unexpected token ILLEGAL
I have tried with several combination of addslash, replace, htmlentites, htmlspecialchars... but I can't get the right one.
What's the right way to work with this in order to avoid any problem?
Thank you.
EDIT:
I have probed this and it seems to work:
In php I use this function:
function javascript_escape($str) {
$new_str = '';
$str_len = strlen($str);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . dechex(ord(substr($str, $i, 1)));
}
return $new_str;
}
and then I use something like
$('<textarea />').html(user).text()
in javascript to decode the string.
Is this safe against XSS attacks?
First, create an HTML-safe JSON string of the array and modify your code to use a data attribute like so:
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Sanitize output
$user = htmlentities($row[0]);
$name = htmlentities($row[1]);
$surnames = htmlentities($row[2]);
$email = htmlentities($row[3]);
$role = htmlentities($row[4]);
$access = htmlentities($row[5]);
$center = htmlentities($row[6]);
$json_str_edit = htmlentities(json_encode(array($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $id)));
$json_str_delete = htmlentities(json_encode(array($row[0], $row[4])));
$message .= "<tr>
<td>" . $user . "</td>" .
"<td>" . $name . "</td>" .
"<td>" . $surnames . "</td>" .
"<td>" . $email . "</td>" .
"<td>" . $role . "</td>" .
"<td>" . $access . "</td>" .
"<td>" . $center . "</td>" .
"<td>" .
"<input type=\"image\" src=\"../resources/edit.png\" id=\"edit_$user\" class=\"edit\" data-user=\"$json_str_edit\" title=\"Editar\"></button>" .
"</td>" .
"<td>" .
"<input type=\"image\" src=\"../resources/delete.png\" id=\"delete_$user\" class=\"delete\" data-user=\"$json_str_delete\" title=\"Eliminar\"></button>" .
"</td>
</tr>";
}
Then create an event listener to catch associated click events in JS like this:
function edit_user(user, name, surnames, email, role, access, center, id) {
// `this` will refer to the html element involved in the event
}
function delete_user(user, role) {
// `this` will refer to the html element involved in the event
}
document.addEventListener('click', function(event) {
if(event.target.hasAttribute('data-user')) {
switch(event.target.className) {
case 'edit':
edit_user.apply(event.target, JSON.parse(event.target.dataset.user));
break;
case 'delete':
delete_user.apply(event.target, JSON.parse(event.target.dataset.user));
break;
}
}
}, false);
Alternatively from the addEventListener method, you can simply add this onclick event listener directly to the element like so (I really don't think it matters in this case):
onclick="edit_user.apply(this, JSON.parse(this.dataset.user))"
FYI It's more common practice to use single quotes in scripts to avoid having to escape the double quote characters. Makes things both cleaner and more standardized.

Using jQuery to get the data of a JSON Object

I am new to jQuery and JSON. I have the following PHP code (getData.php) performs query from the database:
<?php
header('Content-Type: application/json');
....
// some code here
....
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
// convert to integer value if there is a bug after passing json_encode
$rev=intval($info['bIRevNum']);
$name=$info['bIName'];
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
$my_arr[]=array('br'=>$name,'rev'=>$rev);
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// json encode
echo json_encode($my_arr);
?>
After use echo 'json_encode' here I can see the JSON object under this format
[{"br":"itemsb1","rev":37},{"br":"itemb2","rev":45}] on my page.
Now I want to access the integer of rev element of the object (37 and 45) for future usage by jQuery in a different PHP file, lets call it index.php and with the below script
<html>
.....
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value){
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
});
</script>
...
// test here
<!---jquery--->
<div id="div1"><h2>CHANGE >>>> ....!!!!</h2></div>
<button>Calling from different PHP file</button>
</html>
If it is correct, when I click on the button "Calling from different PHP file" it should appears the value of JSON object as 37, 45.
I have tried many ways, but it does not display anything on my page.
Please help me with this!
It appears your problem is that you are echo'ing the html as well as the JSON. try removing the 'echo' from these lines
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
DO NOT delete this line:
$my_arr[]=array('br'=>$name,'rev'=>$rev);
Also make sure your javascript is syntax correct
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value) {
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
Ensure that the only content coming back from getData.php is JSON-formatted; otherwise, it won't be parsed correctly. If you visit getData.php in your browser directly, you should only see JSON content, and nothing else (including errors, warnings, etc.). Your jQuery looks good; so the issue would have to be whatever content is coming back from the PHP script. I just whipped up a trivial test case using this PHP:
<?php
header('Content-type: application/json');
$my_arr[]=array('br'=>'something','rev'=>'2.0.5');
echo json_encode($my_arr);
?>
Using the exact HTML you provided, that works just as expected.

Categories

Resources