PHP, Javascript & Ajax query - javascript

I'm developing a simple filter setup for a side project and have come up to a roadblock.
I'm using the following code to pass a variable to a second php file which does a database query based on the 'GET' variable that has been passed.
<?PHP
$con = mysql_connect("localhost","*********","***********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("drwho", $con);
?>
<!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" />
<script type="text/javascript">
function updateCompanions(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("randomStoryCompanionWrapper").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","updateCompanions.php?doctorID="+str, true);
xmlhttp.send();
}
</script>
<link rel="stylesheet" type="text/css" href="css/css.php" />
<link rel="stylesheet" type="text/css" href="css/css.css" />
<link rel="stylesheet" type="text/css" href="css/randomStory.css" />
<title>Doctor Who Thingy</title>
</head>
<body>
<section id="pageWrapper">
<header></header>
<section id="pageContent">
<section id="pageMainDisplay">
<section id="randomStoryDoctorWrapper">
<section class="randomStorySelectTitle">Doctor</section>
<?PHP
$dValue = 1;
$selectedDoctor = "";
$result = mysql_query("SELECT * FROM doctors ORDER BY doctorid");
while($row = mysql_fetch_array($result))
{
$doctorID = $row['doctorid'];
$doctorTitle = $row['doctorName'];
?>
<button class="randomStorySelectDoctorIcon" value="<?PHP echo $dValue;?>" onclick="updateCompanions(this.value);"><?PHP echo $doctorTitle;?></button>
<?PHP
$dValue++;
}
echo "<section class='end'></section>";
echo "</section>";
?>
<section id="randomStoryCompanionWrapper">
<section class="randomStorySelectTitle">Companion(s)</section>
<section class="randomStorySelectTitle">No Doctor selected</section>
<section class="end"></section>
</section>
<section id="randomStoryMonsterWrapper">
<section class="randomStorySelectTitle">Monster/Adversary</section>
<section class="randomStorySelectTitle"><?PHP echo $selectedDoctor; ?> </section>
<section class="end"></section>
</section>
</section>
<section id="pageAdDisplay">
<section id="pageGoogleAd">Google Ad space</section>
<section id="pageGoogleAd">Random Amazon Item</section>
<section id="pageGoogleAd">Random BBC Item</section>
<section id="pageGoogleAd">Random Big Finish Item</section>
<section id="pageGoogleAd">Random Comixology Item</section>
</section>
</section>
<footer>Footer</footer>
</section>
</body>
</html>
The problem I'm having is getting the 'GET' variable sent back to the original page.
ie. I need to have a new variable '$selectedItem' be populated with the value contained in the 'str' variable that the Javascript function is using.
In my head, it seems as though just assigning the 'GET' variable to the new variable in the 'updateCompanions.php' file would do it, but it doesn't seem to return the variable.
Would anyone know of how, or even if it is possible? (I know the difference between Javascript and PHP in terms of where the processing happens and that passing variables from Javascript to PHP is tricky :))
Thanks
Paul
Here is the code for updateCompanions.php
<?php
$con = mysql_connect("localhost","*********","*********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("********", $con);
$doctorID = $_GET['doctorID'];
if (strlen($doctorID) < 2)
{
$doctorID = "0" . $doctorID;
}
echo "<section class='randomStorySelectTitle'>Companion(s)</section>";
$companions = mysql_query("SELECT * FROM companions WHERE companionDoctor LIKE '%$doctorID%' ORDER BY companionid");
while($row = mysql_fetch_array($companions))
{
$companionID = $row['companionid'];
$companionTitle = $row['companionTitle'];
echo "<button class='randomStorySelectCompanionIcon' value='" . $companionID . " onclick='updateMonsters(this.value);>" . $companionTitle . "</button>";
}
echo "<section class='end'></section>";
?>

Related

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

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.

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();

Infinite scroll isn't working

I Have been going through a tutorial on infinite scrolling and have everything exactly the same except my alert is not being triggered and I cannot work out why. Any possible variations of obtaining the scroll positioning in the IF statement would also be helpful.
<?php
require_once("connect.php");
$results = $connect->query("SELECT * FROM images ORDER BY image_name DESC LIMIT 0,2");
$count = $connect->query("SELECT * FROM images");
$nbr = $count->rowCount();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class='images'>
<?php
while($row = $results->fetch())
{
?>
<p><img src="images/<?php echo $row['image_name'];?>" height="500" width="500"></p>
<?php
}
?>
</div>
<script src='js/jquery.js'></script>
<script>
$(document).ready(function(){
var load = 0;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height())
{
alert("test");
}
});
});
</script>
</body>
</html>
Found the solution. The correct library needs to be called which many sites do not stipulate. Here is the code that needs to be posted just before the scroll script.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

xmlrequest does not return text from php

I need to find some tools to be able to call .php from .html.
Here is a problem:
while this example works, from .php file:
<html>
<head>
<meta http-equiv="content-type" content="text/html" charset="utf-8">
</head>
<body>
<p>Your IP is </p>
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
<hr />
</body>
</html>
this example doesn't echoes IP in .html file:
---from index.html---
<html>
<head>
<meta http-equiv="content-type" content="text/html" charset="utf-8">
<script type="text/javascript">
function getIpNumber() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("showIpNumber").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getip.php",true);
xmlhttp.send();
}
</script>
</head>
<body onload="getIpNumber();">
<p>Your IP is <span id="showIpNumber"></span></p>
</html>
---from getip.php---
<?php
echo "$_SERVER['REMOTE_ADDR']";
?>
what is wrong here?
Change this line
echo "$_SERVER['REMOTE_ADDR']";
to
echo $_SERVER['REMOTE_ADDR'];
having error reporting on would have signaled:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /file.php on line 2
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
As pointed out by Knossos in a comment:
"You can also use echo "{$_SERVER['REMOTE_ADDR']}"; Although in this case, that would be quite pointless. It can be useful in bigger more complicated strings though."
Just replace this line
echo "$_SERVER['REMOTE_ADDR']";
to this
echo $_SERVER['REMOTE_ADDR'];

Categories