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.
Related
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.
I have a JavaScript in HTML file that call a php file in a $.get jquery API. When I run the HTML file on my computer where WAMP is running (for php), I can't get the result of php function on the screen,neither the text of h1 tag nor the the output of print function. Thanks for a lot your answer.
Regards
Here is my html file AJAXTest.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml; charset=iso-8859-1" />
<script type = "text/javascript"
src = "jquery-1.3.2.min.js">
</script>
<script type = "text/javascript">
$(init);
function init(){
alert("init passage 2" + " Andy");
$.get("http://localhost/greetUser.php", { "userName": "Andy" }, processResult);
alert("processresult passage" + data);
$("#output").html(data);
}
function processResult(data, textStatus){
alert("processresult passage" + data);
$("#output").html(data);
}
</script>
<title>AJAXTest.html</title>
</head>
<body>
<h1>Test AJAX</h1>
<div id = "output">
C’est la sortie par défaut
</div>
</body>
</html>
and here is my php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml; charset=iso-8859-1" />
<title>greetUser.php</title>
</head>
<body>
<div>
<h1>Réponse</h1>
<?php
$userName = $_REQUEST["userName"];
print "<p>Salut, $userName!</p> ";
?>
</div>
</body>
</html>
It looks like everything should largely be working, but one thing that I can see that would break it, is that you have the
alert("processresult passage" + data);
$("#output").html(data);
being called inside of the init() function, directly after the $.get call.
At this point in the execution, the 'data' variable does not exist and using it will cause an error and halt all javascript from continuing, as the execution has to wait until the request is returned to be able to process it (in the processResult function, which you appear to be handling correctly)
Removing those lines, I think should solve your problem.
Try this:
<script type = "text/javascript">
init();
function init(){
$.post("http://localhost/greetUser.php", { "username": "Andy" }, function(data,textStatus){
$("#output").html(data);
});
}
</script>
UPDATE
I don't understand the downvote, but if you try this, it works:
<script type = "text/javascript">
init();
function init(){
$.post("http://localhost/file.php", { "username": "Andy" }, function(data,textStatus){
$("#output").html(data);
});
}
</script>
<title>AJAXTest.html</title>
</head>
<body>
<h1>Test AJAX</h1>
<div id = "output">
C’est la sortie par défaut
</div>
</body>
</html>
PHP file:
<?php
$userName = $_POST["username"];
print "<p>Salut, $userName!</p> ";
?>
I have a client who needs to output pages that are referenced by ID in a database. The pages must be output one after another (like a slide show), and there must be a slider transition effect. To make it "fun", the database will be changing as new pages are added, so a portion of the script to do all this must be run repeatedly to check the database.
I've got the pages to load, and I've got the transition working. The problem is, I can't get the polling to work because there's such a mess. That is, if I add a new page, I must manually reload the script - I need the script to detect new pages added to the database. I know that all I really need to do is just re-run the database query to generate the array, but with all the other stuff going on, I'm lost. I've tried setInterval() and even a while loop to no avail. At this point I'm sure I'm just missing something (hopefully) trivial, so I humbly ask for help. My code is VERY sloppy as I test, but here it is:
<?php
$community_id = 89;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// get all the pages that pertain to the community
$uid_query = "SELECT uid FROM pages WHERE pid=" . $community_id;
// build the javascript array by grabbing all results from above query
$result = mysqli_query($con,$uid_query);
$counter = 0;
$baseURL = "http://www.website.com/index.php?id=";
echo "var frames = new Array;";
while($row = mysqli_fetch_array($result)) {
echo "frames[" . $counter . "]='" . $baseURL . $row['uid'] . "';";
$counter++;
echo "frames[" . $counter . "] = 5;";
$counter++;
}
mysqli_close($con);
?>
var i = 0, len = frames.length;
function ChangeSrc()
{
if (i >= len) { i = 0; } // start over
document.getElementById('frame').src = frames[i++];
setTimeout('ChangeSrc()', (frames[i++]*1000));
}
window.onload = ChangeSrc;
</script>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#iframe_container
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="iframe_container">
<iframe src="" name="frame" id="frame" width="100%" height="100%" frameborder="0"></iframe>
</div>
</body>
</html>
... and then any given page looks like this:
javascript:
$(document).ready(function(){
$('.hidden').slideDown(1000);
});
css:
.hidden{
display:none;
}
html:
<div class="hidden">
CONTENT GOES HERE
</div>
this is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Daftar Berita </title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<form method="post" action="">
<?php include 'formpencarian.html.php'; ?>
<div id="newssection" style="margin-top: 50px; clear: both; display: block;">
<?php include 'newssection.php'; ?>
</div>
<?php
if(isset($_POST["cari"])){
echo "<div id='searchsection' style='margin-top: 50px; clear: both; display: block;'>";
include 'search.php';
echo "</div>";
echo "<script>document.getElementById('newssection').style.display = 'none';</script>";
}
?>
<script>
function showMore(id){
document.getElementById('isi'+id).style.display = "block";
document.getElementById('more'+id).style.display = "none";
document.getElementById('less'+id).style.display = "block";
}
function showLess(id){
document.getElementById('isi'+id).style.display = "none";
document.getElementById('more'+id).style.display = "block";
document.getElementById('less'+id).style.display = "none";
}
function advancedSearch(){
document.getElementById('advanced').style.display = "none";
document.getElementById('searching').style.display = "block";
document.getElementById('no').style.display = "block";
}
function noSearch(){
document.getElementById('advanced').style.display = "block";
document.getElementById('searching').style.display = "none";
document.getElementById('no').style.display = "none";
}
</script>
</body>
</html>
basically, the search.php file contains mysql query for displaying results.
the problem is, when this page reloaded (because i sent the POST variable to this page) the javascript doesn't work. as a result, i can't show or hide certain divs on my results page (because the results page is formatted just the same as this page).
Am i doing something wrong?? Please help. Thanks.
in the bigger JS part there are only function definitions, but now calls - to make them run in any case, you need to call them, like:
noSearch();
advancedSearch();
and this part doesn't seem to be related to $_POST checking
..
to avoid not calling them in search.php, you should remove if(isset($_POST["cari"])){ check from your main file and do it inside of the search.php
I am working on a instant search function, currently i am having trouble passing the variable from JS to PHP file. I am also unsure about what to do once i have the results from the query. Any help would be fantastic. This is my current standing.
ERROR
Undefined index: partialSearch in \php\search.php on line 4
test.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AJAX SEARCH</title>
<link rel="stylesheet" href="stylesheets/base.css">
<link rel="stylesheet" href="stylesheets/skeleton.css">
<link rel="stylesheet" href="stylesheets/layout.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
$("#results").html(result);
}});
};
</script>
</head>
<body>
<div class="container">
<div class="one-third column index">
<h3>Search Our Site</h3>
<p>Simply type into the search bar below the video, article you are looking for.</p>
<input type="text" name="partialSearch"onkeyup="search(this.value)"/>
<div id="results"></div>
</div>
</div>
</body>
</html>
search.php
<?php
include 'config.php';
$partialSearch = $_POST['partialSearch'];
$stmt = $mysqli->prepare("SELECT Name FROM videos WHERE Name LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($Name);
while ($row = $stmt->fetch()) {
$searchResults[] = $Name;
echo "<div>".$searchResults."</div>";
}
?>
You should change
data: partialSearch
to
data: {partialSearch: partialSearch} // or {"partialSearch": partialSearch}, which is the same
Where partialSearch is the data's index name.
1.) You did not tell jQuery to post, e.g.
$.ajax({ type: "POST", ... });
You can also use the shorthand ".post" :
$.post{url:"PHP/search.php",data: partialSearch,success:function(result){ $("#results").html(result);
2.) The PHP thinks of a named POST variable. So your partialSearch must be an object like so
partialSearch = { partialSearch : "I AM your variable, NOT the object holding me !!!" }
By default, $.ajax calls sends a GET request, so your $_POST is not valid in your .php file, unless you specify a ..type:"POST".. variable in your $.ajax(.. settings.
Secondly, you need to change this:
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
to this:
$.ajax({url:"PHP/search.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){
It's perfectly ok to pass an object of variables to send.