Javascript timer refresh and php function [duplicate] - javascript

I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);

It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation

Related

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

How can I trigger PHP if a MySQL gets a new highest ID?

Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");

Multiple AJAX functions on one functions page

I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.

Jquery AJAX is working but displayed message bugged

In changename.php I have this DIV:
<div id="resultDiv"></div>
In the same file I have the PHP code:
<?php
include_once ('connect.php');
if(isset($_POST['name']))
{
$postedname = $_POST['name'];
$safename = mysqli_real_escape_string($con, $postedname);
$checkname = "SELECT * from accounts where name='$safename' LIMIT 1";
$query = mysqli_query($con, $checkname);
$row = mysqli_num_rows($query);
if($row) {
echo 'Name is already taken!';
} else {
$changename = "UPDATE accounts SET name='$safename' WHERE Name='$_SESSION[username]'";
$query = mysqli_query($con, $changename);
if($query)
{
echo 'Name is changed!';
$_SESSION['username'] = $safename;
}
}
}
?>
And this is my Jquery script (in a seperate file):
$(function(){
$("form").submit(function() {
event.preventDefault();
var name = $('#inputName').val();
$.post("changename.php",
{
name: name
},
function(data)
{
$("#resultDiv").text(data);
});
});
});
The code is just working fine, it successfully changes my name. If I want my name to be 'John', it successfully changes it in the DB.
The problem is, it's supposed to change the div with ID resultDiv to Name is already taken!. Instead of that, it takes the whole changename.php HTML code and puts it into that DIV. So instead of 1 line, I have 100+ lines of my page in there. So it looks like this:
https://gyazo.com/9320a5f15ed67a8ad9298d6172ab6909
Any idea why it's not just the message I want?
Ajax will fetch all data from file given as url for it.
If you want to avoid that, you have 2 options.
Write condition in changename.php in such a way that only update to db part will be executed.
On changename.php keep only required code to update to db.

Pull down updates when user click on updates

Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}

Categories

Resources