I'm trying to make a notification to my simple php/js chat:
First, I'm trying to compare my log.html (which containing the messages):
my original post.php ( //jQuery request. It posts the client's input and data being sent to the post.php file each time the user submits the form and sends a new message.) The. post.php is saving the messages into log.html file.
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
my edited post.php (trying to set up a function, which is checking the "new" message - comparing with old ones).
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
// Check if content is different
function text_check(){
$ah = fopen("log.html", 'rb');
$aha = preg_match(fread($ah, 8192), $text_message);
$result = true;
while(!feof($ah)) {
if( $aha === false){
$result = false;
break;
}
}
fclose($ah);
return $result;
}
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
If post.php function "text_check()" return true in my index.php:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function checkUpdate()
{
$.post("post.php", function(text_check){
if (text_check.toString()=="true") {
playSound();
}
});
}
function playSound()
{
var audio = new Audio('my_audio');
audio.play();
}
Is it a OK conception?
And how can I make an "orang-red blinking" notification, when browser is minimized?
I read something about title - have to change it. Will it work, if I change it every second with JS?
Related
let me first say that I'm no expert in web development so I might have made a stupid mistake but no amount of googling seems to be helping. I need to have a single html page (preprocessed in php) to display occasional events fired by a "server" page residing on the same machine.
I've readapted the basic w3schools server sent events example as follows and it seemed to be working fine until last night, but today (still working when first tested) I added a simple table and a ref to an external (empty) js file to the html and events stopped being caught by the page. I decided to roll back to the working code but even that doesn't work anymore. I had to remove the files and restore from a backup!
I'm sure the sse.php code is being run since part of what it does is removing records from a sqlite3 database and that's happening.
Here's the code, I really hope you can help me because I really have no idea what's happening.
This was tested on Linux + Xampp + Firefox and sadly this is a mandatory combination, having it work under other conditions is not useful at the moment. (fyi: opening the mon.php page in Opera gave me a single event and then stopped working as well)
Thank you all.
mon.php
<?php
if ( ! isset($_GET['mon']) ) {
die('mon code missing');
}
?>
<html>
<head>
<script type="text/javascript">
var evtSourceUrl = "sse.php?mon=" + <?php echo '"'.$_GET['mon'].'"'?>;
if(typeof(EventSource) !== "undefined") {
var source = new EventSource(evtSourceUrl);
source.onmessage = function(event) {
document.getElementById("info").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("info").innerHTML = 'sse not supported';
}
</script>
</head>
<body>
<p>
<span id="info"></span>
</p>
</body>
</html>
sse.php
<?php
function output_sse($msg) {
echo "data: " . $msg . "\n\n";
ob_end_flush();
flush();
}
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$mon = null;
if ( isset($_GET["mon"]) ) {
$mon = $_GET["mon"];
} else {
output_sse('mon code missing');
die();
}
while ( true ) {
usleep(1000 * 100);
$db = new PDO("sqlite:ch.sqlite3");
if ( $db === false ) {
output_sse('err:PDO');
die();
}
$stmt_select = $db->query("SELECT * FROM CH WHERE IDMON='$mon';");
$stmt_delete = $db->prepare("DELETE FROM CH WHERE IDMON='$mon';");
$db->beginTransaction();
$res = $stmt_select->fetch();
$stmt_delete->execute();
$db->commit();
$db->close();
if ( strlen($res['TK']) > 0 && strlen($res['SP']) > 0 ) {
$msg = "$res['TK'] :: $res['SP']";
output_sse($msg);
}
}
?>
add.php (to add new records to be displayed - this works)
<?php
$mon = isset($_GET["mon"]) ? $_GET["mon"] : die ('mon code missing') ;
$tk = isset($_GET["tk"]) ? $_GET["tk"] : die ('tk code missing') ;
$sp = isset($_GET["sp"]) ? $_GET["sp"] : die ('sp code missing') ;
$db = new SQLite3('ch.sqlite3');
if ( $db === false ) {
die('Cannot open db');
}
$res = $db->exec("INSERT INTO CH('IDMON','TK','SP') VALUES('$mon','$tk','$sp');");
if ( $res != 1 ) {
echo 'insert failed';
}
if ( $db->close() === false ) {
die('Cannot close connection to db');
}
echo('ok');
?>
This seems to be a problem related to the PDO interface in the sse.php file. I replaced it with the SQLite3 class like the add.php file and everything started working fine. The transaction seemed to get stuck.
I am using a jQuery plugin (http://www.runningcoder.org/jqueryvalidation/) to validate data on the client-side. If all goes well, the user is to be directed to another page when he hits submit. This works just fine if I comment out the plug-in script section, but does not when it is included.
I am a bit perplexed honestly. I do not get a 'headers already sent' message, and I thought the plug-in would stop from ever even going to the server if the data was invalid - meaning that it should make on a bit of difference to the PHP if it is included or not.
What am I missing?
the beginning of my main PHP page
require('scripts/mailer/PHPMailerAutoload.php');
include('header.php');
$ssn = $_SESSION['userSSN'];
$last = $_SESSION['userLast'];
if($_SESSION['verified']) {
$verified = true;
}
// CODE OMITTED... //
$mailer = new PHPMailer;
$mailer->addAddress("insurance#insurancemidam.com");
$mailer->addAttachment($zipName);
$mailer->Subject = "Insurance Enrollment";
$mailer->Body = "Testing";
if(!$mailer->send()) {
echo "<h2>Error Submitting form. Please check your input and try again</h2>";
} else {
unlink($zipName);
header("Location:success.php");
}
}
the tail end of my main PHP
echo "<input type='submit' name='submitInsurance' value='Submit' /></form>";
}
include('footer.php');
?>
<script>
$("#mainForm").validate({
submit: {
settings: {
errorListContainer: '.formGroup',
}
}
});
footer.php
<?php
echo "</div><footer>Copyright Mid-America Hotels Corporation " . date("Y") . "</footer></html>";
header.php
<?php
session_start();
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
require('includes.php');
$host = '';
$user = '';
$pass = '';
$db = new dataBaseAccess($host, $user, $pass);
// if user is attempting to login...
if(!isset($_POST['submitInsurance'])) {
if(isset($_POST['login'])) {
$user = formatInput($_POST['user']);
$ssn = formatInput($_POST['ssn']);
if($db->verifyUser($user, $ssn, 'insurance_validation')) {
$_SESSION['verified'] = true;
$_SESSION['userLast'] = $user;
$_SESSION['userSSN'] = $ssn;
header('Location: insurance.php');
}
else {
echo "<!doctype html><head><link rel='stylesheet' href='styles/base.css' /><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script><script src='scripts/validation.js'><script src='scripts/base.js'></script><title>Insurance Mid-Am</title></head><body><header><img src='logo.png' alt='Mid-America Hotels'><h1>Insurance Enrollment</h1></header><div id='mainContent'><h2 class='error'>Invalid Login Credentials!</h2>";
}
}
else {
echo "<!doctype html><head><link rel='stylesheet' href='styles/base.css' /><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script><script src='scripts/validation.js'></script><script src='scripts/base.js'></script><title>Insurance Mid-Am</title></head><body><header><img src='logo.png' alt='Mid-America Hotels'><h1>Insurance Enrollment</h1></header><div id='mainContent'>";
}
}
?>
EDIT: The reason is that, for some reason, $_POST['submitInsurance'] is not getting sent. Using var_dump, it appears the other data gets sent, but the button's value. Why might this be?
Hi I have the following code which I am trying to adapt to make sure that when Like is clicked by a user who is logged in, then only one request is sent in a predetermined period of time that can be adjusted i.e Like can be clicked and a request sent only once every 5 minutes. There must be a javascript function I can use but I can't figure it out.
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else {
alert(data);
}
});
}
like.php:
<?php
function add_like($userid) {
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?
like_add.php
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
If you pass the a tag into like_add like so:
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(this, '.$userid.');">Like</a>';
?>
You can disable it in the javascript function for a set time period:
function like_add(a, userid) {
a.disabled = true;
setTimeout(function(){
a.disabled = false;
), 5000});//Code will execute in 5 seconds to enable the a tag
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
}else{
alert(data);
}
});
}
Is this something alogn the lines of what you were looking for?
In a completly not recommended way, you could define
var isLikeable = true;
function likeStatus(secs) {
isLikeable = false;
window.setTimeout("isLikeable = true;", (secs*60));
}
then, when clicking the "like" you would check
if (isLikeable) { // do like and call likeStatus(300); }
Do you need this to be enforced on the back-end, or is disabling it through the UI sufficient? You could theoretically get people hacking it using Developer tools or Firebug, but this seems very unlikely from casual users.
On the front end, I would user jQuery to add code on the click event that disables the "Like" button with a timeout, like this:
// First, move your click handler to your script file
$('.like').click( function(event) {
// Make sure clicking the button doesn't submit any form context that might be present
event.preventDefault();
var DURATION_IN_MINUTES = 5;
// Grab the user id that will be added as an attribute of your element: data-user-id="$userid"
var user_id = $(this).data('userID');
// Run your function
like_add(user_id);
// Disable clicking like (it's easiest to do this with a button, by far
$(this).prop({'disabled':true,'title':'Disabled for ' + DURATION_IN_MINUTES + ' minutes');
// Set a timer to re-enable the like button in 5 minutes
setTimeout( function() { $(this).prop({'disabled':false,'title':''}), DURATION_IN_MINUTES * 60 * 1000}
});
and then in your HTML:
echo '<a class="like" href="#" onclick="like_add(', $userid, ');">Like</a>';
becomes
echo '<button class="like" data-user-id="' + $userid + '">Like</button>';
I don't have a PHP environment to test this (and I haven't tested the JavaScript itself, to be honest), but this should be enough to get you started.
If you want to block multiple submissions on the back-end, you'll want to timestamp your likes, and do a look-up to see the last time a given user "liked" that link.
I've create a code that check if a variable is empty or not.
If the variable is empty I execute a javascript alert, in particular:
if($verbo_name == NULL)
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
If I insert a message inside the echo, the message appears correctly, but I want show the alert in javascript. What's the error? Thanks..
UPDATE more details:
$results = $con->query("SELECT verbo, descrizione FROM verbo WHERE verbo = '$verbo'");
$verbo_name = NULL;
while($row = $results->fetch_array())
{
$verbo_name = $row['verbo'];
}
Check below codes are working fine for me.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
?>
Check this one
if(empty($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
This should trigger an alert:
<html>
<body>
<?php
if($verbo_name == NULL)
{
$msg = enter code here'no record available in the database';
} else {
$msg = 'not set';
}
echo "
<script>
alert('". $msg ."');
</script>";
?>
</body>
</html>
If the message is not set the problem is just the variable.
This is Pravat Kumar Sahoo's answer,
This must work fine.
If you are testing on google chrome, you might have prevented the alert dialog message mistakenly. Please try clearing the cache/cookie or test on any other browser.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "<script>alert('no record available in the database');</script>";
exit();
}
?>
Update:
Instead of alerting the message inside PHP, echo a message, like "NoData". And in the ajax calling Javascript, receive response "success".
echo "NoData"; // In PHP file.
In your Javascript, get the response,
success:function(response)
{
if(response == "NoData");
{
alert("No data in the Database");
}
}
How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){