Refresh mysql div content using ajax - php

Could somebody please point me in the right direction as regards refreshing a particular div using ajax. I know the basics of php, a little jquery, but Zero ajax. My scoreboard is built using php within a table as follows -
<div class="scoreBoard">
<table>
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
</table>
</div>
At the moment I have a little refresh image that refreshses the page onClick via JS. The idea of an ajax refresh would be much nicer.

save your php code in a file named somename.php then call it with
ajax
in somename.php
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
in your main file
<div class="scoreBoard"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
setInterval( refreshScoreBoard, 5000 );
var inRequest = false;
function refreshScoreBoard() {
if ( inRequest ) {
return false;
}
inRequest = true;
var load = $.get('somename.php');
$(".scoreBoard").html('Refreshing');
load.error(function() {
console.log( "Error" );
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".scoreBoard").html('<table>'+res+'</table>');
});
load.done(function() {
console.log( "Completed" );
inRequest = false;
});
}
</script>

smth. like this in some event triggered function(can be time interval either):
$('.scoreBoard').load('path/to/php_fetching_data_and_building_table');
For more information (like sending post/get) check here:
jQuery - load
ps: you can also use 'ajax' jquery function

Related

Trying to show data from Mysql table to wordpress page using html code widget

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.

php: onClick event - table

How to use onclick in table?
The following code is my basic code.
php code
$con = mysqli_connect($db_host,$db_user,$db_passwd,$db_name);
mysqli_set_charset($con, "utf8");
$result = mysqli_query($con, "select * from Marker_DB");
echo "<table border=’1′> <tr> <th>num</th> </tr>";
$n = 1;
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['num'] . "</td>";
echo "</tr>";
$n++;
}
echo "</table>";
mysqli_close($con);
I've made a lot of attempts to use onclick. Here's how I tried:
code
echo "<td>". "onclick='displayComment($row['num'])" . "</td>";
echo "<td onClick="'www.google.com/'">". $row['num'] . "</td>";
How can I use onclick in php?
Give your table some id,
echo "<table border='1′ id='table-id'> <tr> <th>num</th> </tr>";
Then your td will be as it is,
echo "<td>". $row['num'] . "</td>";
In js just write this code and check,
$("#table-id").on("click", "td", function() {
alert($(this).text()); // see if you get the value of $row['num']
// you can play here as you like
var num = $(this).text();
displayComment(num);
});
function displayComment(num) {
// your code
}
What you need to do is to stop the propagation of the parent event when a child is clicked, it's easy done in jQuery, but naively you need to do a little more work:
function displayComment(num){
//Do your stuffs with num
console.log('td clicked');
};
Note, for Firefox you need to pass a event parameter:
<td onclick="displayComment($row['num'])">Column 3</td>

Can't get Post value ID from row table to PHP using Jquery

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.

Refresh page / result after Ajax call

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/

How can AJAX handling be incorporated into a PHP/MySQL While Loop (for asynchronous editing)?

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.

Categories