I have some jQuery that handles a click event on a table row,which is built with PHP, when it is clicked. It works fine as long as the table is built in the same file. It however will not work if I have jQuery go out to a PHP file, have the PHP build the table, then send the output back to be written in a div tag. I have tried adding .live to the event but that didn't work either? Any suggestions?
The html and jQuery:
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var name;
var text;
var subject;
var id;
var key;
$(document).ready(function(){
buildMsgTable();
//Load Message Data in click
$('#messages tr').click(function(){
$(this, 'tr').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
return $(td).text();
});
key = lines[0];
name = lines[1];
textarea = lines[2];
subject = lines[3];
//alert(textarea);
$('#name').val(name);
$('#subject').val(subject);
$('#body').val(textarea);
})
});
function buildMsgTable(){
$.post('/php_webfiles/edit/buildMsgTable.php',
{},
function(output){ $('#existingMessagesDiv').html(output); });
}
</script>
</head>
</body>
<div id='existingMessagesDiv'></div>
<div id = 'debug'></div>
</body>
</html>
And the php called by buildMsgTable:
<?php
include "hawkfunctions.php";
$tsql = "SELECT * FROM Messages";
$conn = mssqlConnect();
$stmt = sqlsrv_query($conn, $tsql);
//$stmt2 = sqlsrv_query($conn, $tsql2);
if ($stmt1 === false) {
echo "Error in query preparation/execution (contacts_in_list).<br/>$tsql1<br/>";
//die( print_r( sqlsrv_errors(), true));
echo "Errors while connecing attempting to run query:<br/><ol>";
$i = 1;
foreach (sqlsrv_errors() as $masterError) {
$errorlist .= "<li>Heading $i<ol>";
foreach ($masterError as $root => $error) {
if (!is_numeric($root)) {
$errorlist .= "<li><b>$root:</b> $error</li>\n";
}
}
$errorlist .= "</ol></li>\n";
$i++;
}
$errorlist .= "</ol>";
die($errorlist);
}
echo "<table border='1' id= 'messages'><th>Key</th><th>Name</th><th>Text</th><th>Subject</th>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo "<tr><td class='key'>";
echo $row['MessageKey'];
echo "</td>";
echo "<td class = 'name'>";
echo $row['Name'];
echo "</td><td class = 'text'>";
echo $row['Text'];
echo "</td><td class = 'subject'>";
echo $row['Subject'];
echo "</td>";
echo "<td class = 'delete'>";
echo "<input type='button' value='Delete' id='delete' onclick='deleteMessage(".$row['MessageKey'].")' />";
echo "</td>";
echo "</tr>";
}
/* Free statement and connection resources.*/
sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn);
echo "</table>";
?>
Think I cut out all the fluff that doesn't pertain to my question.
Related
I am trying to show MYSQL query results in tabular form on a WordPress page using an HTML code snippet. When I show the data on a single HTML code widget then the data shows perfectly. But, when I try to show the data on multiple html widgets then the same data shows on each widget.
Here is my jQuery written-in HTML code widget to fetch data from the PHP file.
Jquery code in widget 1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery( document ).on('submit_success', function( event, response ){
read();
});
jQuery( document ).ready(function( $ ){
read();
});
function read() {
$.get( "api/data.php", function( data ) {
document.getElementById("table1").innerHTML = data;
});
}
</script>
<table id="table1"></table>
Jquery code in widget 2
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery( document ).on('submit_success', function( event, response ){
read2();
});
jQuery( document ).ready(function( $ ){
read2();
});
function read2() {
$.get( "api/profile.php", function( data ) {
document.getElementById("table2").innerHTML = data;
});
}
</script>
<table id="table2"></table>
And here is the code in the api/data.php file to fetch data from the MySQL table
$user = wp_get_current_user();
$email=$user->user_email;
$conn = new mysqli("localhost","<table name>","<user name>","<password>");
$result = mysqli_query($conn, "SELECT * FROM table where email='$email' ");
echo '<tbody>';
echo '<tr>';
echo "<th> Email </th>";
echo "<th> Name </th>";
echo '</tr>';
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
}
echo "</tr>";
echo '</tbody>';
And here is the code in the api/data2.php file to fetch data from the MySQL table
$user = wp_get_current_user();
$email=$user->user_email;
$conn = new mysqli("localhost","<table name>","<user name>","<password>");
$result = mysqli_query($conn, "SELECT * FROM table where email='$email' ");
echo '<tbody>';
echo '<tr>';
echo "<th> Phone </th>";
echo "<th> Address </th>";
echo '</tr>';
while($row1 = $result->fetch_assoc()) {
echo '<tr>';
echo "<td>" . $row1['phone'] . "</td>";
echo "<td>" . $row1['address'] . "</td>";
}
echo "</tr>";
echo '</tbody>';
Everything is working fine. But no luck when I try to show data on another HTML code widget using different table names from different PHP files. showing same data in both HTML widgets.
I know that my question may be duplicate, but I've looked through a ton of questions with the same problem, but none of the solutions worked for me.
It's pretty simple, get the item-id value and POST it to del.php.
I can't get the POST value in the php after the click.
<?php
include '../include/db.php';
$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
$("tr").click(function() {
var id = $(this).find('.item-id').text();
$.post('del.php',{id: id},function(json){
window.location.href = "http://localhost/unesc/3/admin/del.php";
}, "json")
});
</script>
del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo $id;
} else {
echo "erro";
}
?>
The del.php just get the $_post['id'] and echo it.
The window.location is there so i won't have to enter the address manually.
The trigger may not be necessarily a Click, it can be a Button, woks just fine for me too.
EDIT: got the POST running with $.ajax, but now, with firebug i noticed that the post in del.php keeps returning empty.
EDIT2: got the del.php post response, but as an error, it says that 'id' don't exist.
If THIS is what you need here is the code of both pages I used
del2.php
<script type="text/javascript" language="javascript" src="jquery.min.js"></script>
<?php
//include '../include/db.php';
include 'includeconnect.php';
//$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
$result = mysql_query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysql_fetch_array($result))
{
echo "
<table border='1'>
<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>
</table>
</br>";
}
echo"<div id='show_responce'>I am a text on page del2.php and I am pretty much useless apart from showing you where the responce will display</div>"
?>
<script type="text/javascript">
$("tr").click(function() {
var rep = $("#show_responce");
var id = $(this).find('.item-id').text();
var dataString = 'id=' + id;
$.ajax({
type: 'post',
url: 'del.php',
data: dataString,
success: function(html) {
rep.empty().append(html);
rep.fadeIn("slow")
}
});
});
</script>
Here is your modified del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo "I am coming from del.php and the ID you clicked on is $id";
} else {
echo "error";
}
?>
By the way because of my account's low reputation I could not ask you what was you trying to do with this window.location but whatever. Instead of what you asked for which was basically to make sure that del.php gets the value of id as you will see I displayed it on del2.php which is the page I am making the request from.
$( "table > td" ).find( ".item-id" ).val();
or
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr id='row'>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script>
var id = [];
var values = [];
$("#row > .item-id").each(function(index){
id.push($(this).attr("id")); // [a,b,c,....]
values.push($(this).text()); //[ Dummy1, Dummy2, Dummy3, Dummy4,..]
});
</script>
Possible errors:
}, "json") here last argument means, that function expects you return valid JSON string from del.php file.
After window.localtion.href you can't access previous data, because it redirects to another page, and thus you loose all your previous data.
I hope this is not a duplicate but I have not found it yet.
To be honest I found this method online and and cant find where I original found it or I would search there for the answer. The below is a test page I am testing my code.
My question is this how do I keep the clock value in the href and add the cellnumber to the href ?? Right now I get dropdowntest.php?cellnumber=8&?clock=8 which is the same value as the cellnumber I believe is in the line:
+ ['?cellnumber', $(this).val()].join('=') + ['&?clock', $(this).val()].join('=');
I have tried changing $(this) on the clock but I could not find the correct syntax.. below is all the code:
<?php
session_start();
require('/db_connection/connect.db.php');
require('settings.php');
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clock').on('change', function() {
location.href = location.href.split('?')[0]
+ ['?clock', $(this).val()].join('=');
});
$('.cellnumber').on('change', function() {
location.href = location.href.split('?')[0]
+ ['?cellnumber', $(this).val()].join('=') + ['&?clock', $(this).val()].join('=');
});
});
</script>
<?php
$clock = mysqli_query($connection, "SELECT username FROM user WHERE wocreate = 1 and hide = 1");
echo "<select class='clock' name='clock' style='width:200px'>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($clock)){
echo "<option value='".$row['username']."''>".$row['username']."</option>";
}
echo "</select>";
if (isset($_GET['clock'])) {
$_SESSION['clock'] = $_GET['clock'];
echo "<p></p>";
echo 'Person Requesting Ticket is '.$_SESSION['clock'].'';
echo "<p></p>";
}
?>
<?php
echo "<br>";
$cellnumbers = mysqli_query($connection, "SELECT DISTINCT location FROM machinenumber WHERE status = 1 ");
echo "<select class='cellnumber' name='cellnumber' style='width:200px'>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($cellnumbers)){
echo "<option value='".$row['location']."''>".$row['location']."</option>";
}
echo "</select>";
if (isset($_GET['cellnumber'])) {
$_SESSION['cellnumber'] = $_GET['cellnumber'];
echo "<p></p>";
echo 'Person Requesting Ticket is '.$_SESSION['clock'].'';
echo "<br>";
echo 'Cell '.$_SESSION['cellnumber'].' is the location';
echo "<p></p>";
}
?>
<?php
if (isset($_GET['cellnumber'])) {
$cellnumber=$_GET['cellnumber'];
echo "<h3>Choose Machine Number</h3>";
$machinenumber = mysqli_query($connection,"SELECT number FROM machinenumber WHERE location =".$cellnumber." ;");
echo "<select class='machinenumber' name='machinenumber' style=width:200px>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($machinenumber)) {
echo "<option value='".$row['number']."'>".$row['number']."</option>";
}
echo "</select>";
}
?>
So I have a php file printing out result in a table from my database and when i mark a result using checkbox, it sends this variable to a new page deleting it. The problem is, in the same page as he Jquery code is in, all the result is displayed, and I want the result to be updated after something is deleted. Tried using window.location.reload(true); in the Ajax code, but now it only delete one result at the time. Some way to relode the page or refresh the result?
In my sakerselect.php: here it print out all result in my database containg checkbox:
$sql = "SELECT * FROM WHERE Kundenr LIKE '".$_GET['kundenr'] ."'ORDER BY CAST(Status as varchar) DESC ";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt == false){
die( print_r(sqlsrv_errors(), tue) );
}
echo "<table id='div2' border='1'>";
echo "<tr><th></th><th>Saksnr</th><th>Saksinfo</th><th>Eier</th> <th>Status</th></tr>";
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH))
{
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
sakerselect is included in my KundeDisplay.php page.
KundeDisplay.php is also containing this ajax code sending the marked values to sakerdelete.php:
<script type="text/javascript">
$('#deletesaker').on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/sakdelete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
window.location.reload(true);
}
});
} else {
alert("Please select items.");
}
});
</script>
In my sakdelete.php file:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
$sql = "DELETE FROM Saker Where Saksnr = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
you can delete one record at a time by this method
If You want to delete two are more record at a time
try this ....
http://www.codexworld.com/delete-multiple-records-from-mysql-in-php/
SCROLL TO FIND WORKING CODE
I am working on a AJAX editing platform, and I am having trouble with setting up the text field for editing.
My code so far:
The Javascript below handles the initial submission:
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function edit()
{
var doc_id = document.getElementById("doc_id").value;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
document.getElementById('content').innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
The SQL below handles the initial select query and display of that information:
$query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured`, ';
$query.= 'FROM `primary_physicians` AS pp ';
$query.= 'ORDER BY pp.`physician_id` ';
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
echo "<td><div id='content'><input id='doc_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' value='Edit' onclick='edit();'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
And the 'ajax.php' file handles the request when the user clicks the 'Edit' button within the 'content' div.
$client_id = $_GET['doc_id'];
$client_query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured` ';
$client_query.= 'FROM `primary_physicians` AS pp WHERE pp.`physician_id`=' . $client_id . '';
$client_result = mysql_unbuffered_query( $client_query );
while ($client_row = mysql_fetch_assoc($client_result))
{
echo "<input type='text' value='$client_row[physician_first_name]' />";
}
What shows is below:
Initial page load:
Pressing the 'edit' button (any of the available buttons, not just the one associated with the client/ID):
Pressing any edit button shows client ID #2 within client ID #1's table row (not in the row with client ID #2):
I'm guessing I have to set up something within the content div and somehow associate it with the 'edit()' function, however I can't figure out how to do that without setting the script within the while loop (which I really don't want to do).
WORKING CODE BELOW
Javascript (initial submission and display):
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function hello(e)
{
/* this was once document.getElementById("doc_id").value;*/
var doc_id = e.currentTarget.id;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
/*this was without the '+doc_id' document.getElementById('content').innerHTML = ajax.responseText; */
document.getElementById('content'+doc_id).innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
PHP/MySQL:
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
//note change to the 'content' div (addition of $physician_id to make it truly unique; this ties into the javascript above.
echo "<td><div id='content$physician_id'>";
//note changes to input id and button id, as well as the 'onclick' function.
echo "<input id='doc_id_$physician_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' id='$physician_id' value='Edit' onclick='hello(event);'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
No changes to or initial MySQL query or to ajax.php
There is a problem with the elements' ids. Remeber that the id attribute should be unique inside a document. You are using the same id for numerous elements:
td><div id='content'><input id='doc_id' type='hidden' ...
inside a loop.
Then you use the Javascript document.getElementById('doc_id'). JS supposes there is only one element with this id on the page so it will always return the first element it finds.
EDIT:
You will have to also change your JS function to retrieve the proper value:
for the edit buttons use: onclick="edit(event)"
And then in the JS:
function edit(e) {
buttonId = e.currentTarget.id;
//use the button id to find the proper value
}
Of course you will have to set the id on the "edit" buttons and have it correspond with id of you inputs. E.g. use $i for the button id and doc_id_$i for the input id.
I also recommend having a look at jQuery, as it will help facilitate many of the things you're trying to achieve here.