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.
Related
I am currently reading through a piece of code provided by my faculty and I am having troubles understanding how it works.
Specifically how the anchor is linked to the php without method="post" or method="get".
Kindly appreciate if anyone could explain or link me to relevant materials to do further readings. Much thanks.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Cart for bought items indexes is created in session if it's not there yet.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
When link with buy query parameter is opened, buy value is added to session cart. After that page is redirected to location without buy parameter.
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
List of items to buy is printed on page (i quess code in question is not full).
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Links open pages with GET method.
Link query parameters can be accessed by special $_GET variable
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."¶m2=".$weekEnd."¶m3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."¶m2=".$weekEnd."¶m3=".$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."¶m2=".$weekEnd."¶m3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."¶m2=".$weekEnd."¶m3=".$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 + "'¶m2='" + weekEnd + "'¶m3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>
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");
}
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.
I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!