I want my client side web to auto-refresh when data in my Database updated, when adding or deleting data I have succeeded however when the data changed, it still fails.
This is my code for checking data from database:
<script>
var row1 = "<?php echo $variable; ?>";
var processUpdate = function( response ) {
var x = response;
//console.log(x);
if (row1 != x) {
window.location.reload();
}
}
var checkUpdates = function() {
serverPoll = setInterval(function() {
$.get('check.php', { lastupdate: 1 }, processUpdate, 'html');
}, 1000)
};
$(document).ready(checkUpdates);
</script>
check.php:
$query = mysqli_query($koneksi, "SELECT * FROM table");
$number = mysqli_num_rows($query);
echo $number;
What should I change to be automatically refreshed if every data in the table is changed?
You can use trigger that will insert some info about each table update in another table, and then just query the num rows on 'changes' table in a similar way you check for new ones here:
DELIMITER //
CREATE TRIGGER table_update_trigger AFTER UPDATE ON table
FOR EACH ROW BEGIN
INSERT INTO table_history
(
change
)
(
NEW.some_value,
);
END
//
The advantage of this solution is you don't need to introduce/rely on/maintain any other db system like Redis and the checking code is not responsible for keeping and updating any counters and queries for updates, inserts and deletes in a similar fashion. Also you might extend the table_history table to log all the fields you are interested in in terms of tracking changes and end up having useful changelog for the purpose of the application.
Related
Edit: Im using XAMPP with built in Apache, vscode
I make a live search input(html>js>php>js>html) , it run smoothly at first key-in, but it's getting slower and slower when i delete and key-in again , wonder what's causing the delay and how to fix it.
And i have a question,
For this example , it is better to use jquery or pure javascript?
Thank you
html
<div>
<input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters">
<div class="result"></div>
</div>
js
$(document).ready(function(){
$(document).on("keyup input",".search",function(){
var input = $(this).val();
var result = $(this).next(".result");
if(input.length){
$.get("table.php", {term: input}).done(function(data){
result.html(data);
});
} else{
result.empty();
}
});
});
php
<?php
$link = mysqli_connect("localhost", "root", "******", "crypto");
// Check connection
if($link === false){
die("ERROR: " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
$coin = "show tables from crypto where Tables_in_crypto LIKE ?";
//prepare the statement
if($prepare = mysqli_prepare($link, $coin)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($prepare, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($prepare)){
$result = mysqli_stmt_get_result($prepare);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["Tables_in_crypto"] . "</p>";
}
} else{
echo "<p>no result</p>";
}
} else{
echo "ERROR: $coin. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($prepare);
}
// close connection
mysqli_close($link);
?>
<script type="text/javascript" src="data.js"></script>
JavaScript
Don't use "keyup input", use just the "input" Event.
Trim $(this).val().trim() your input values, you don't want an empty space to trigger a search for data!
Cooldown! You don't want to perform an additional AJAX ($.get()) request while one is already on the way. Instead create a setTimeout throttle which - only once the user stopped typing for N milliseconds the request will be triggered.
A pseudocode logic to picture it is quite simple:
jQuery($ => { // DOM ready and $ alias in scope
const search = ($input) => {
const input = $input.val().trim(); // Trim your strings!
const $result = $input.next(".result");
if (!input) {
$result.empty();
return; // end it here
}
$.get("table.php", {term: input}).done((data) => {
console.log(data);
// Exercise for the reader:
// Make sure data is an Object
// create "<p>" elements with text and populate $result
});
};
let searchCooldown; // Search input cooldown
$(document).on("input", ".search", function() {
clearTimeout(searchCooldown); // clear occurring search timeout
searchCooldown = setTimeout(() => {
search($(this)); // will be triggered once user stops typing for 300ms
}, 300); // 300ms seems like a good typing timeout?!
});
});
No, you don't need jQuery. The Fetch API is mature enough.
PHP
Don't place <script> tags inside a PHP file — which its only job should be querying the data from a database and returning it.
Don't return HTML from PHP! That's a waste. You might want a PHP file to return JSON data instead - that way it can be used by your HTML page, your watch, fridge, etc. It's usually done using echo json_encode($result);. If you need to attach also an "error" property to your $result data JSON, do so.
I don't deserve a credit for myself because everything i find mainly is on stackoverflow (after many hours spent) just I model everything to my own needs and like to give back in return.
If your page has no pagination a nice and easy way to live search all the items in javascript by doing the following (the html code may not be related to the script):
-you need to use XPath in chrome dev tools, to get the element needed:(right click on an element node->Copy -> copy full xpath)
-lets say we want to search for all the <h2> text tags inside :
-in blade file we have products.blade.php:
<html>
<body>
<input type="text" placeholder="search" id="search" onkeyup="myFunction()"></input>
<ul id="myList" class="myList-class">
<li><h2>item 1<h2></li>
<li><h2>item 2<h2></li>
</ul>
//the script below is not related to the tags above, but just to give you an idea.
<script>
function myFunction() {
var lis = document.querySelectorAll('.columns-3.products.snip-ul > li');//get all the <li> tags, change it to your needs(get the value from Ranorex selocity extension in chrome).
var x = document.getElementById("search").value; //item to search for(textbox)
if (document.getElementById("search").value.length == 0) { //if nothing is typed in textbox get all the products back
lis.forEach(node=>node.setAttribute("style","display:flex")); // restore all the display attribute to flex
return;
}
for (var i = 1; li = lis[i-1]; i++) {
var searchTitles = ((document.evaluate('/html/body/div[1]/ul/li[' + i + ']/div/div[2]/a/h2/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data);
//change the above xpath to your own needs : (document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data;
// li.parentNode.removeChild(li);
if (searchTitles.toLowerCase().includes(x.toLowerCase())) {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:flex";
} else {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:none"; //hide all <li> tags
}
}
}
</script>
I'm currently developing a web application and I am using PHP 8.0.3.
For some reason, the Ajax request is not capable of getting the updated value of the SESSION variable unless I forcefully refresh the page. I am calling the ajax function first when the page finishes loading, and then every minute.
I am using AJAX to update the values on a CanvasJS graph.
Can someone help me identify what am I doing wrong?
First, I start the session on a global file that I require on the scripts.
session_name("mfm");
session_start();
Snippet of my current ajax request on index.php page:
$.ajax({
method: "POST",
url: "php_func/somefile.php",
success: function(data){
console.log(data);
var dbdata = JSON.parse(data);
var qtyNuts = [];
var time = [];
dbdata = dbdata.reverse();
for (i = 0; i < dbdata.length; i++) {
time[i] = dbdata[i][1];
qtyNuts[i] = dbdata[i][0];
}
...
And this is part of the php_func/some_file.php:
if(isset($_SESSION['bar']))
{
$processed = $_SESSION['bar'];
$max = count($processed);
if($max > 5)
{
$max = 5;
}
$recent_data = array_slice($processed, -$max);
foreach($recent_data as $data)
{
$kgs = $data[0] / 120.0;
array_push($kgdata, array($kgs, $data[1]));
}
echo json_encode(array_reverse($kgdata));
}
I typed /php_func/some_file.php on my localhost URL and it works, kgdata array is getting updated as the SESSION variable updates.
And this is a snipped of where the session variable is created (this script runs as soon as the page is loaded and then every minute). Update.php:
$bar = array()
if(isset($_SESSION['bar'])
{
$bar = $_SESSION['bar'];
}
$b = array(count($buffer), date("H:i:s"));
array_push($bar, $b);
$_SESSION['bar'] = $bar;
For some reason, the ajax request does not update the values in the index.php graph, unless I forcefully refresh the page. What am I doing wrong?
I tried
Checking session id. They are the same in all files.
Use $.post instead. I have the same issue.
Change the setInterval for the ajax function to be more than a minute in case there is clashing between update.php and somefile.php
Hi everyone, I have 4 parts of my code
2 html buttons (Activate User, Delete User)
a html table
jquery on getting user_id on html table
php script in executing update or delete sql command
Scenario:
I have a html table (the data are pulled from the SQL DB using a php script) I can select the rows on the table and extract their user_id flawlessly but the problem is that I have these two buttons (Activate User, Delete User) everything works well until you put their codes together the problem is that the activate php script takes command and not the delete user script. Is their a "break;" on php scripts just like switch cases so that it won't execute the other instead it executes the script specifically for those two buttons.
These are my buttons
<a type="button" id="activateUser"> Activate Selected User</a>
<a type="button" id="deleteUser"> Delete Selected User</a>
This is the jQuery script for highlighting my html table row
<script>
$('tr').click(function ()
{
$('tr').removeClass('selected');
$(this).addClass('selected');
selectedRow = $(this);
});
This is the jQuery script for getting the id for my button and getting the user_id on Activate Selected User button.
$("#activateUser").click(function ()
{
var td = $(selectedRow).children('td');
for (var i = 0; i < 1; ++i) {
window.location.href = window.location.href+'?id='+td[i].innerText;
}
});
This is the jQuery script for getting the id for my button and getting the user_id on Delete Selected User button.
$("#deleteUser").click(function ()
{
var td = $(selectedRow).children('td');
for (var i = 0; i < 1; ++i) {
window.location.href = window.location.href+'?id='+td[i].innerText;
}
});
This is the PHP SCRIPT for activating the user by changing the user_active to 1 which activates the user
<?php
$id = $_GET['id']; //gets the user_id from as GET request
$btnQuery = "SELECT * FROM users WHERE user_id='$id'";
$buttonquery = mysqli_query($DBLink, $btnQuery);
$Actcount = mysqli_num_rows($buttonquery);
$act = 1;
if($Actcount == 1)
{
$sqlact = "UPDATE users SET user_active='$act' WHERE
user_id='$id'";
$activate = mysqli_query($DBLink, $sqlact);
if($activate)
{
echo $ActivatedUser = "<b>Success!</b> User successfully Activated.";
echo "<script>setTimeout(function()
{
window.location.replace('http://localhost/webpage/manage-user.php');
}, 1500);
</script>";
}
}
?>
This is the PHP SCRIPT for deleting the selected user
<?php
$id = $_GET['id'];
$btnQuery = "SELECT * FROM users WHERE user_id='$id'";
$buttonquery = mysqli_query($DBLink, $btnQuery);
delcount = mysqli_num_rows($buttonquery);
if($delcount == 1)
{
$sqldel = "DELETE FROM users WHERE user_id='$id'";
$delete = mysqli_query($DBLink, $sqldel);
if($delete)
{
echo $Deleted = "<b>Success!</b> User successfully Deleted.";
echo "<script>setTimeout(function()
{
window.location.replace('http://localhost/webpage/manage-user.php');
}, 1500);</script>";
}
}
?>
THE CODE STRUCTURE
[ACTIVATE USER] BUTTON
SCRIPT FOR SELECTING ROW IN HTML TABLE
SCRIPT FOR GETTING THE user_id FOR USER ACTIVATION
PHP SCRIPT ON ACTIVATING
[DELETE USER] BUTTON
SCRIPT FOR SELECTING ROW IN HTML TABLE
SCRIPT FOR GETTING THE user_id FOR USER DELETION
PHP SCRIPT ON DELETING
Again, it works well without the other half or vice versa, but when I try to combine them it never executes and it even executes only the first part or sometimes bugs. I tried using exit() or die() at the end of each php script but it makes matters worst.
Thanks Everyone.
You need to add a parameter to your URL that indicates which action you want:
$("#activateUser").click(function ()
{
var td = $(selectedRow).children('td').first();
window.location.href = window.location.href+'?action=activate&id='+$(td).text();
}
});
$("#deleteUser").click(function ()
{
var td = $(selectedRow).children('td').first();
window.location.href = window.location.href+'?action=delete&id='+$(td).text();
}
});
Then in your PHP script you check $_GET['action']:
if ($_GET['action'] == 'activate') {
// code for activating account
} elseif ($_GET['action'] == 'delete' {
// code for deleting account
} else {
die("Invalid action");
}
I have a javascript variable called "list". I need to send it as a POST data to another page and open that page in a new tab (with the POST data present).
This code:
jQuery.post('datadestination.php', list);
sends the data all right, but ofcourse it opens the page in the same tab.
I saw some solutions to similar problems using invisible form and things like that, but I could not get them to work. Is there any simple solution?
You can send a form using the target="_blank" attribute.
<form action="datadestination.php" method="POST" target="_blank" id="myform">
<input type="hidden" name="list" id="list-data"/>
<input type="submit" value="Submit">
</form>
Then in JS:
jQuery('#list-data').val(list);
jQuery('#myform').submit();
This is an implementation of Sergey's solution.
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
// So even if someone passed _POST[isAdmin]=true, all that he would do
// is populate _SESSION[data][isAuthenticated], which nobody reads,
// not the all-important _SESSION[isAuthenticated] key.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
In the first page:
$.post('save.php', { data: list }, function(response){
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status !== 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open('datadestination.php');
});
And in datadestination.php add the fix:
if (!array_key_exists('data', $_SESSION)) {
die("Problems? Did you perchance attempt to reload the page and resubmit?");
// For if he did, then yes, $_SESSION would have been cleared.
// Same if he is operating on more than one window or browser tab.
}
// Do something to validate data. For example we can use data.timestamp
// to assure data isn't stale.
$age = time();
if (array_key_exists($ts = 'data.timestamp', $_SESSION)) {
$age -= $_SESSION[$ts];
}
if ($age > 3600) {
die("Data is more than one hour old. Did someone change server time?!?");
// I actually had ${PFY} do that to me using NTP + --hctosys, once.
// My own time zone is (most of the year) exactly one hour past GMT.
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data'], $_SESSION['data.timestamp']);
// keep things clean.
// From here on, the script behaves "as if" it got a _POST.
Update
You can actually merge save.php and datadestination.php and use a "saving stub" savepost.php that you can recycle in other pages:
<?php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
// Timestamp sent by AJAX
if (array_key_exists('ts', $_POST)) {
// TODO: verify ts, but beware of time zones!
$_SESSION['data'] = $_POST['data'];
Header("Content-Type: application/json;charset=UTF-8");
die(json_encode(array('status' => 'OK')));
}
die("Error");
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data']); // keep things clean.
?>
Now your call becomes
$.post('datadestination.php', { data: list, ts: Date.now() }, function(){
window.open('datadestination.php');
});
and in your datadestination.php (or anywhere else) you add
require 'savepost.php';
I suggest:
Pass that list with the jquery.post() function and save it in the SESSION array.
Open a new tab with the same file/address/URL with the window.open() function.
Retrieve saved data from the SESSION array.
This seems straightforward and clean to me.
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});