Can't add sound alert on every new message on chat website - javascript

I'm building a chat website and i want to add a sound alert whenever a new message is sent so i can alert other users for new unread messages(i use MySQL for storing messages etc.). I use ajax to get the messages from the database and put them on my chatbox. I tryied every way but it doesn't seen to work idividually on every NEW message. Please help!
That's my index.php
<?php
session_start ();
define('DB_HOST', 'localhost');
define('DB_NAME', '*******');
define('DB_USER','*****');
define('DB_PASSWORD','********');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Chat2Chat!</title>
</head>
<body id="body-color">
<?php
if (! isset ( $_SESSION ['user'] )) {
header ( "Location: sign-in.html" ); // Redirect the user
} else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">
Καλωσήρθες, <b><?php echo $_SESSION['user']; ?></b>
</p>
<p class="logout">
<b class="submitmsg" id="exit" href="#">Logout</b>
</p>
<div style="clear: both"></div>
</div>
<div id="chatbox" class="chatbox">
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" autofocus/>
<input class="submitmsg" name="submitmsg" type="submit" id="submitmsg" value="Αποστολή"/>
</form>
</div>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
setInterval ( "get()", 2000 );
});
//jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Είσαι σίγουρος πως θέλεις να αποσυνδεθείς;");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
loadLog;
return false;
});
setInterval (loadLog, 2500);
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatbox").html(data);
var scroll = document.getElementById('chatbox');
scroll.scrollTop = scroll.scrollHeight;
}
});
}
</script>
<?php
}
?>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
The chat.php
<!DOCTYPE HTML>
<head>
<title>Chat</title>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
</head>
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_57218');
define('DB_USER','u57218');
define('DB_PASSWORD','27222528');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error());
$query = "SELECT * FROM Messages";
if($result = mysqli_query ($con, $query)){
while ($row = mysqli_fetch_row($result))
{if($row['4']==0){
echo '('.$row['5'].') <b>'.$row['1'].'</b>: '.$row['2'].'<br>';
}
else{echo 'Ο χρήστης <b>'.$row['1'].'</b> '.$row['2'].'<br>';}
}
mysqli_free_result($result);
}
mysqli_close($con);
?>

You can store the last message id which you played sound for, and at every refresh action, you can check if the last message id is equals to id you stored before. If not, you play sound.
To be more clear:
$lastMessageId=5;
$lastMessageIdWePlayedSoundFor=4;
if($lastMessageId!=$lastMessageIdWePlayedSoundFor)
{
////play sound here
$lastMessageIdWePlayedSoundFor=$lastMessageId;
}
So whenever there is a new message we haven't played a sound for it's existance, we play sound. You can use this algorithm.

Related

Affecting returned PHP query result to HTML form input field

Contents of main file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test JSON</title>
<style type="text/css">
body {
margin : 100px;
}
h1 {
text-align: center;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$("#btn").click(getNewVal);
});
function getNewVal(){
var xhr = new XMLHttpRequest();
var queryString = "getVal.php?str=" + "Blah";
xhr.open("GET", queryString, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//alert(document.getElementById("txtField").value);
var JSONObj = JSON.parse(xhr.responseText);
alert(JSONObj.item);
document.getElementById("txtField").value = JSONObj.item;
}
}
xhr.send(null);
}
</script>
</head>
<body>
<h1>Test JSON</h1>
<hr />
<form id="testForm" method="GET" action="">
<label>Custom Value: </label>
<input type="text" value="La valeur a changer" id="txtField">
<input type="submit" value="Bouton pour changer la valeur" id="btn">
</form>
</body>
Contents of ajax call file
<?php
if (mysqli_connect_errno())
{
echo "Problème avec la connection : " . mysqli_connect_error();
}
else{
if(isset($_GET['str'])) {
$val = $_GET['str'];
$post_data = array('item' => $_GET['str']);
echo json_encode($post_data);
}
else{
echo "error";
}
}
?>
I want to return the result of the query and affect it to an html text input field in another php file. After making the changes for JSON everything works, except the document.getElementById("txtField").value = JSONObj.item; in the onreadystatechange. What am i missing?
Thanks in advance!

Send JSON data from one page and receive dynamically from another page using AJAX when both page are open

I am trying to send JSON data from page1 on submit button click and try to receive this data dynamically from page2 using AJAX and print the data in console. I don't know the proper syntax to do this. One suggested code which is not appropriate. The code is given:
page1:
<?php
if(isset($_POST["submit"])){
$x = "ok";
echo json_encode($x);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>page1</title>
</head>
<body>
<p>This is page is sending json data on submit button press</p>
<form method="post">
<input type="submit" name="submit">
</form>
</body>
</html>
page2:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
</head>
<body>
<p>Get json data from page1 dynamically using ajax</p>
<script>
setInterval(checkVariableValue, 5000);
function checkVariableValue() {
$.ajax({
method: 'POST',
url: 'page1.php',
datatype: 'json',
success: function(data) {
console.log(data);
}
});
}
</script>
</body>
</html>
What should I write to make it works properly?
You can do like this
session_start();
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST["submit"])){
$value = 'I am test'; //can be any value
$_SESSION['key'] = $value;
} else if($_SERVER['REQUEST_METHOD']=='POST')){
echo $_SESSION['key'];
}

Why does these two arguments fetch the same value?

I'm learning Ajax using PHP as back-end. What I'm trying is fetching and updating the table values from database using setTimeout in JavaScript.
Here's my code:
(I've explained the problem below)
A. ex1.php
<?php
$a=mysqli_connect("localhost", "root", "", "ndb");
$query="SELECT name from tab3";
$queryrun=mysqli_query($a, $query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery-2.2.0.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
var update= setTimeout(myFunc2, 4000);
function myFunc2(){
var yhttp= new XMLHttpRequest();
yhttp.onreadystatechange=function(){
//if(yhttp.readyState==4 && yhttp.status==200)
};
yhttp.open("GET", "exresponse2.php", true);
yhttp.send();
}
</script>
<script>
var cmp= setTimeout(cmpFunc, 100);
function cmpFunc(){
var h="";
var h2="";
var cmp2= setTimeout(cmp2Func, 2000);
function cmp2Func(){
h= '<?php $height=mysqli_num_rows($queryrun); echo $height; ?>';
}
var cmp3 =setTimeout(cmp3Func, 8000);
function cmp3Func(){
h2= '<?php $height2=mysqli_num_rows($queryrun); echo $height2; ?>';
if(h==h2)
{
alert(h+" "+h2);
}
else
{
alert("Not same");
}
}
}
</script>
</head>
<body>
<div id="id1" style="float: left; width: 300px">
The names are displayed below:</div>
<div id="id2" style="float: left; width: 200px">
<button onclick="myFunc2()">Submit</button>
</body>
</html>
B. exresponse.php
<?php
$a=mysqli_connect("localhost", "root", "", "ndb");
$query="SELECT name from tab3";
$queryrun=mysqli_query($a, $query);
$names=array();
while($row=mysqli_fetch_assoc($queryrun))
{
$names[]= $row["name"];
}
$x="";
$count=0;
for($x=0; $x<25; $x++)
{
echo "Name: ".$names[$x];
echo "<br>";
}
?>
<html>
<head>
<script src="jquery-2.2.0.js"></script>
</head>
<title></title>
<body>
</body>
</html>
As you can see, when the page ex1.php is opened on browser, after 100 micro seconds cmpFunc executes, then after 2 seconds cmp2Func executes and variable h is assigned some value; and after 2 more seconds myFunc2 executes (which updates table on database). After that, cmp3Func executes and variable h2 is assigned value.
But every time, only if statement executes. But actually the table should be updated between h and h2 are assigned values, and they should have DIFFERENT values. Am I doing something wrong here?
The reason h and h2 are always the same is that when ex1.php is first rendered to the client, the values for the javascript are hardcoded for h and h2 at that instant in time, so they are the same every time you call that js function later.
I think a solution would involve moving the sql block for $query="SELECT name from tab3"; to another server page that you would then hit with an ajax call inside your cmp3Func function.

How to store captured image path in mysql database using php.?

I want to capture image from webcam user image that image stored in specified folder and captured image path store into mysql using php. I have an problem with webcam captured image path is not stored in mysql database. so please help me...
<script src="webscript.js"></script>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="webcam.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
var shutter = new Audio();
shutter.autoplay = false;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
Webcam.upload( data_uri, 'upload.php', function(code, text) {
alert(data_uri);
});
} );
}
</script>
<?php
include 'connection.php';
// be aware of file / directory permissions on your server
$newname = move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.date('YmdHis').rand(383,1000).'.jpg');
$query = "INSERT INTO entry(name) VALUES('".$_GET['url']."')";
mysql_query($query)or die(mysql_error());
echo "<script>alert('successfully..');</script>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Javascript Webcam</title>
<link href="font-awesome.min.css" rel="stylesheet"/>
<link href="bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<center>
<div class="row">
<div class="col-md-6">
<h3>Profile Picture</h3>
<div id="my_camera"></div>
<!-- A button for taking snaps -->
<form>
<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div id="results" class="well">Your captured image will appear here...</div>
</div>
</div>
</center>
</body>
</html>
Assuming $mysqli is a successfully connected [new Mysqli] object.
$query = "SELECT * FROM 'database.table' WHERE 'somecolumn'='someval' LIMIT= 5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();

refreshing a <div> with ajax but passing along a counter variable

I have two .php files. The first one ajax_testing.php looks like this:
<!DOCTYPE html>
<html>
<?php
$index_local=1;
$_SESSION['global_index'] = $index_local;
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="main">Who is batman? click count=<?echo $_SESSION['global_index'] ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?php echo $_SESSION['global_index']; ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
Document number two is called property-detailed.php and looks like this:
<!DOCTYPE html>
<html>
<?php
$_SESSION['global_index'] = $_GET['global_index'];
?>
<head>
<script></script>
</head>
<body>
<div id="main">Who is batman? click count=<?php echo $_SESSION['global_index']; ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait til page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?echo $_SESSION['global_index'] ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
I load the first page, and it has a variable, $global_index, that is set to 1 and a button with an ajax command to reload the div with the new information found on the second page.
My goal is to have the variable $global_index carry over and increment each time I press the button. Is this possible with only ajax being implemented? If so, is there a way to make it happen with only the first page? Otherwise would it just be easier to have my database keep track of this number and increment that?
In your ajax_testing.php:
<?php session_start(); ?>
<script type="text/javascript" src="jquery.js"></script>
<?php
$_SESSION['counter'] = 1;
$count = $_SESSION['counter'];
?>
<div id="main">Batman<?php echo $count; ?></div>
<button id="detailed">Link</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#detailed',function(){
var count = "<?php echo $count; ?>",
dataString = "counter=" + count;
$.ajax({
type: "POST",
url: "property-detaild.php",
data:dataString,
success:function(data){
$('#main').html(data);
console.log(data);
}
});
})
});
</script>
And in your property-detailed.php:
<?php
session_start();
$_SESSION['counter'] = $_SESSION['counter']+1;
echo $_SESSION['counter'];
?>

Categories