I'm working on a little PHP MYSQL chat app. I need to refresh the data in the chat window every few seconds without reloading the entire page. I know I have to use Javascript or Jquery to accomplish this but I don't really know them good enough.
Below is the code that creates the chat window and populates it from the database.
Thanks so much, appreciate the help.
<textarea id="screen" name="screen" style="width:100%;height:300;resize:none">
<?php
$sql="SELECT * FROM `$tbl_5` WHERE advertid='$advertid' ORDER by id ASC";
$result = mysqli_query($dbconn, $sql);
while ($row2=mysqli_fetch_row($result))
{
echo $row2[5]."\n";
}
?>
</textarea>
EDIT: My attempt using AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
type: 'POST',
url: '/chatrefresh.php',
data: parameters,
success: function(response){
$('#chatwindow').html(response);
},
error: function(response){
alert(response);
},
complete: function() {
setInterval(sendRequest, 5000);
}
});
};
});
</script>
<table id="chatwindow" name="chatwindow"><tr><td></td></tr></table>
Chatrefresh.php
<textarea id="screen" name="screen" style="width:100%;height:300;resize:none">
<?php
include_once('session.php');
include('config.php');
$advertid=$_SESSION['advertid'];
$sql="SELECT * FROM `$tbl_5` WHERE advertid='$advertid' ORDER by id ASC";
$result = mysqli_query($dbconn, $sql);
while ($row=mysqli_fetch_row($result))
{
echo $row[5]."\n";
}
?>
</textarea>
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I'm building a webshop for a project at university. I have a search bar in header, navigation bar on the left. In both cases I send data with Ajax (from search bar a keyword, from navs a category and subcategory). Ajax response is a PHP script that prints products based on category and subcategory or keyword. At the end of it it prints pagination links and select element for number of products per page. If I submit a keyword or click on a nav, it prints out results fine, but if I then change the page or a number on select element (another Ajax request) , the results default because category/subcategory or keyword are not being sent anymore. This is the code for search bar request:
$("#searchButton").click(function(){
$("#searchBar").blur();
var keyword=$("#searchBar").val();
$.ajax({
type:"GET",
url:"print.php",
data: { keyword:keyword }
}).done(function (data){
$('#content').html(data);
return false;
});
});
and this is the code for pagination:
$(document).on("change", "#paginationSelect", function(){
var productsPerPage=$("#paginationSelect").val();
$.ajax({
type:"GET",
url:"print.php",
data: { productsPerPage:productsPerPage }
}).done(function (data){
$('#content').html(data);
return false;
});
});
I'm wondering what's the best way to save the data sent by last Ajax request so that I can send it again while changing pagination stuff. Should I change the PHP file or Ajax requests and what's the best way to do it?
Edit:
This is the PHP file:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect("localhost", "root", "") or die("Couldn't connect to database.");
mysql_select_db("webshop") or die("Couldn't select a database.");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
if(isset($_GET["category"]) & isset($_GET["subcategory"])){
$category=$_GET["category"];
$subcategory=$_GET["subcategory"];
$query="SELECT * from proizvod where kategorija='".$category."' and podkategorija='".$subcategory."'";
}
else if(isset($_GET["keyword"])){
$keyword=$_GET["keyword"];
$query="SELECT * from proizvod where ime like '%".$keyword."%'";
}
else{
$query="SELECT * from proizvod";
}
$result=mysql_query($query);
$numProducts=mysql_num_rows($result);
if(isset($_GET["productsPerPage"]))$productsPerPage=$_GET["productsPerPage"];
else if($numProducts>=10) $productsPerPage=10;
else $productsPerPage=$numProducts;
if(isset($_GET["pageNum"]))$pageNum=$_GET["pageNum"];
else $pageNum=1;
if(isset($keyword)) print "<div id=\"keywordMessage\" class=\"col-lg-12\">Traženi pojam: ".$keyword."</div>";
if(mysql_num_rows($result)==0) print "<div class=\"col-lg-12\">Nema rezultata</div>";
for($i=0;$i<($pageNum-1)*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
}
for($i=($pageNum-1)*$productsPerPage;$i<$pageNum*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
print("<div class=\"col-lg-6\">
<table class=\"article\">
<tr><td colspan=\"2\"><img src=\"images/".$row["id"].".jpg\" class=\"imgArticle\"/></td></tr>
<tr><td colspan=\"2\"><b>".$row['ime']."</b></td></tr>
<tr><td>Kategorija: </td><td>".$row['kategorija']."</td></tr>
<tr><td>Opis: </td><td>".$row['opis']."</td></tr>
<tr><td>Cijena: </td><td>".$row['cijena']." kn</td></tr>
</table>
</div>");
}
print("<div class=\"col-lg-12\" id=\"paginationControl\">
<span class=\"col-lg-4\">
Prikazano: ".(($pageNum-1)*$productsPerPage+1)."-".$pageNum*$productsPerPage."/".$numProducts."
</span>
<span class=\"col-lg-4\" id=\"pageNumbers\">");
if($productsPerPage!=0){
for($i=1;$i<=ceil($numProducts/$productsPerPage);$i++){
if($i==$pageNum) print($i."   ");
else print("<a class=\"pageNumControl\" href=\"#\">".$i."</a>");
}
}
print("</span>
<span class=\"col-lg-4\">Proizvoda po stranici:
<select id=\"paginationSelect\">
<option value=\"10\" "); if($productsPerPage==10){ print("selected");} print(">10</option>
<option value=\"20\" "); if($productsPerPage==20){ print("selected");} print(">20</option>
<option value=\"30\" "); if($productsPerPage==30){ print("selected");} print(">30</option>
<option value=\"50\" "); if($productsPerPage==50){ print("selected");} print(">50</option>
</select>
</span>
</div>");
mysql_free_result($result);
?>
You could use jQuery .Data(). But please note, if you refresh the entire page, the .data() information is lost.
So, without have more code this is the best example I could come up with. I am storing the search information in the #searchBar's data, then retrieving it on pagination change.
$("#searchButton").click(function() {
var $sb = $("#searchBar"),
keyword = $sb.val();
$sb.data({
prevKeyword: keyword
}).blur();
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: keyword
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
$(document).on("change", "#paginationSelect", function() {
var productsPerPage = $("#paginationSelect").val(),
previousKeyword = $("#searchBar").data('prevKeyword');
// Do something with the keyword
console.log(previousKeyword);
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: previousKeyword,
productsPerPage: productsPerPage
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
Newbie in AJAX here, I want to requery or select *from again on my database on button click and change the textarea content? How do I do that using AJAX.
Here is my code.
<textarea id="CKUPDATEALL">
<?php
$result = mysqli_query($con,"SELECT *FROM home WHERE ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 0,1");
while($row = mysqli_fetch_array($result))
{
echo $row['ANNOUNCEMENTS'];
}
?>
</textarea>
No you can set your php file to check against different variables being passed in the Ajax call. The in the Ajax response success look for the different variables that were defined in the php file. So you might call Ajax.php for 10 different Ajax calls and responses. Just have to set it up properly.
$(document).ready(function(){
$("#my_button").on('cick',function(){
Var name = $('#thisinputid').val();
$.ajax({
url: "getval.php",
type: "POST",
data : { fullname : name },
success: function(data) {
$("#CKUPDATEALL").val(data);
}
});
});
Then in the php file check for $_post['fullname'].
Say this is your button
<input type="button" id="my_button" value="Cick"/>
Ajax
$(document).ready(function(){
$("#my_button").on('cick',function(){
$.ajax({
url: "getval.php",
type: "POST",
data : {'type':'textarea'},
success: function(data) {
$("#CKUPDATEALL").val(data);
}
});
});
And in getval.php
<?php
if(isset($_POST['type']) && trim($_POST['type']) == 'textarea'){
$result = mysqli_query($con,"SELECT * FROM home WHERE ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 0,1");
while($row = mysqli_fetch_array($result)){
echo $row['ANNOUNCEMENTS'];
}
die();
}
?>
Try $.ajax() like,
$(function(){
$.ajax({
url:'get_announcement.php',
type:'POST',
data:{type:'announcement'},
success:funtion(d){
$('#CKUPDATEALL').val(d);
}
});
});
get_announcement.php
<?php
// type is announcement
if(isset($_POST['type']) and $_POST['type']=='announcement'){
$result=mysqli_query($con,"SELECT * FROM home WHERE
ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 1");
while($row = mysqli_fetch_array($result)){
echo $row['ANNOUNCEMENTS'];
}
echo 'not found';
}
?>
I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.
I have this code on my page...
the jQuery
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
This is the get_posts.php
<?php
include('dbconnect.php');
session_start();
$uid= $_SESSION['uid'];
$get_ids=mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($get_ids)){
$id=$row['id'];
$sm=$row['message'];
}
$get_lpid=mysql_query("SELECT * FROM users WHERE uid='$uid'");
while($row_o = mysql_fetch_array($get_lpid)){
$l_pid=$row_o['lastviewed'];
}
if($id!=$l_pid){
$insert=mysql_query("UPDATE users SET lastviewed='$id' WHERE uid='$uid' ");
if($insert){?>
<div class='media'><img src='img/profile_pictures/thumbs/thumb_13718921232_119055628287843_1500172795_n.jpg' class='img-circle post-circle pull-left'><div class='media-heading'><a href='#'>Pratik Sonar</a><div class='pull-right'><small>12.00PM</small></div></strong></div><div class='media-body'><?php echo $sm ?></div></div>
<?php } else{
}
}
else{
}?>
This technique seems to work on every browser except chrome. I have tested ie, safari, firefox and opera all are working. Can anyone enlighten me on this thing? Is there something I don't know or am I missing?
Try to wrap your code into this function:
$(document).ready(function() { ... });
Like:
$(document).ready(function() {
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
});
You're probably better off using setTimeout() too.
Now the code runs when the DOM is fully loaded.
Why are you using window.setInterval?
It's simply setInterval(), without any parent.
Try
$(document).ready(function() {
setInterval(function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});
},10);
});
Thank You guys for all your concerns. Well at last the bug got fixed by this chunk of code. I guess setTimeout gain gains victory over setInterval
$(document).ready(function() {
window.setTimeout(function(){
$.ajax({
type: "GET",
url: "php/get_posts.php",
}).done(function( data ) {
$('.post-container').prepend(data);
});
},10);
});