I am trying to populate a select box from values from a mysql database, using jQuery.
db call:
<?php
include 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$tableName = "tbl_title";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
//echo json_encode( $data );
?>
HTML:
<select id="a1_title">
<option>Default</option>
</select>
There are a bunch of examples that I have found, but nothing specifically related to what I am looking for, unless the force is not with me today.
Is there a link someone can point me to?
The below script will load the dropdown list from the JSON received from the PHP Page.
$(function(){
var items="";
$.getJSON("yourPHPPage.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.Name+"</option>";
});
$("#a1_title").html(items);
});
});
Assuming the received JSON is in this format
[ { "ID" :"1", "Name":"Scott"},{ "ID":"2", "Name":"Jon"} ]
Another thing i noticed is that you are doing SELECT * FROM table name to get the items. I do not think you should do that. You should do only two columns (ID & NAME , if you you have those columns in your table.).
Here is a JSFiddle example to show how to fetch data from the JSON.
// retrieve value and text from ajax
var html = "<option value=\""+value+"\">"+text+"</option>";
$("#a1_title").append(html);
I have same problem, your suggestion is work
HTML & JS
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("get-data.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#a1_title").html(items);
});
});
</script>
<select id="a1_title">
<option>Default</option>
</select>
</body>
</html>
php
include 'configurations/db-connections.php';
$q = "select id, name from college";
$sql = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
Related
This question already has answers here:
jquery serialize and multi select dropdown
(6 answers)
Get the values of 2 HTML input tags having the same name using PHP
(4 answers)
Closed 6 years ago.
I want to change the status in the database, with a select dropdown field.
I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc
I tried with serialize(), but its not working.
select from database:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var allbooks = $(this).val();
var dataString = "allbooks="+allbooks;
$.ajax({
type: "POST",
data: dataString,
url: "get-data.php",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<?php
define("HOST","localhost");
define("USER","root");
define("PASSWORD","");
define("DATABASE","hotel");
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
if (mysqli_num_rows($resultRooms) > 0) {
echo "<div id='reserved' align='center'>";
While ($row = mysqli_fetch_array($resultRooms)) {
echo $row[1];
echo $row[0];
?>
<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php
for($i=1; $i<=19; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select><br />
<?php }
}
else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>
and getting the results:
if(!empty($_POST["allbooks"])) {
var_dump($_POST);
$id = 2;
//echo $_POST['modelS'];
$room = $_POST['allbooks'];
$sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
$query = mysqli_query($euConn, $sql2);
var_dump($query);
}
How to change, or what would be a simple solution? Thanks for the help.
You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....
As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.
I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)
It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.
<?php
require_once ("db_config.php");
function updateRoom($euConn, $newRoomVal, $id)
{
$stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
$stmt->bind_param('ii', $newRoomVal, $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
$stmt->close();
return $affectedRows;
}
function getRooms($euConn)
{
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
$rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
}
function createSections($rows)
{
$sections = [];
foreach( $rows as $row){
$options = [];
for ($i = 1; $i <= 19; $i++)
$options[] = "<option value=" . $i . ">" . $i . "</option>";
$options = implode('', $options);
$select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
// .. build all your other row elements here....
$section = 'some other compiled html'.$select;
$sections[]=$section;
}
return implode('', $sections);
}
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
$updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
echo json_encode(['success'=>$updated]);
exit;
}
$pageSections = getRooms($euConn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var $this = $(this);
var allbooks = $this.val();
var rowId = $this.data('row-id');
var dataString = "allbooks="+allbooks+'&rowId='+rowId;
$.ajax({
type: "POST",
data: dataString,
url: "",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<div id='reserved' align='center'>
<?php echo $pageSections ?>
<div id="show">
</div>
</body>
</html>
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});
I'm making a timeline graph and I have problem with the data I need the result of the query to the database did not result in double quotes ("). They leave a sample of how I get the result
[{"name":"Tv Cable","data":["[1370925000000,100]"]},{"name":"Tv Satelital","data":["[1365654600000,100]","[1368505800000,200]","[1370320200000,1500]","[1370925000000,500]","[1370925000000,560]","[1370925000000,50]","[1370925000000,500]","[1370925000000,800]","[1370925000000,500]","[1373776200000,1000]"]},{"name":"Tv Internet","data":["[1371097800000,500]"]},{"name":"Tv Telefonia"}]
I need it follows
[{"name":"Tv Cable","data":[[1370925000000,100]]},{"name":"Tv Satelital","data":[[1365654600000,100],[1368505800000,200],[1370320200000,1500],[1370925000000,500],[1370925000000,560],[1370925000000,50],[1370925000000,500],[1370925000000,800],[1370925000000,500],[1373776200000,1000]]},{"name":"Tv Internet","data":[[1371097800000,500]]},{"name":"Tv Telefonia"}]
I have while trying to fix it and I have not managed to do?
I let my graphic codes to see what I do
sql.php
<?php
$fecha = date("d-m-Y"); // fecha actual
$ano = date("Y"); // A単o actual
$mes = date("m"); // Mes actual
$dia = date("d"); // Dia actual
$mes_inicio= $mes-2;
$con = mysql_connect("localhost","xyolcarx_inter","xYolcar19572059");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xyolcarx_inter", $con);
$rows = array();
for ($i=1;$i<=4;$i++){
$sth = mysql_query("SELECT monto,(unix_timestamp(fecha)*1000) FROM ventas WHERE codigo_ser = '".$i."' ORDER BY fecha ASC ");
$sth2 = mysql_query("SELECT * FROM servicio WHERE codigo_ser= '".$i."'");
while($r2 = mysql_fetch_array($sth2)) {
$rows[$i]['name'] = $r2['servicio'];
}
while($r = mysql_fetch_array($sth)) {
$rows[$i]['data'][] = '['.$r['(unix_timestamp(fecha)*1000)'].','.$r['monto'].']';
}
}
$result = array();
for ($i=1;$i<=4;$i++){
array_push($result,$rows[$i]);
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(function() {
$.getJSON('sql.php', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : data
});
});
});
//]]>
</script>
</head>
<body>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
This line
$rows[$i]['data'][] = '['.$r['(unix_timestamp(fecha)*1000)'].','.$r['monto'].']';
should look like this
$rows[$i]['data'][] = array($r['(unix_timestamp(fecha)*1000)'],$r['monto']);
Don't build the json yourself. Just build the array structure, and let json_encode do the rest of the work for you.
edit more advice:
Change this:
SELECT monto,(unix_timestamp(fecha)*1000) FROM ventas...
to this:
SELECT monto, (unix_timestamp(fecha)*1000) AS fecha_timestamp FROM ventas...
so you can access it easier in php:
$rows[$i]['data'][] = array($r['fecha_timestamp'],$r['monto']);
edit more advice:
Mysql sometimes has performance issues with unix_timestamp(fecha)*1000 because it has to turn what it thinks was an 32-bit int into a 64-bit int, and that sucks. Do that in php.
Change this:
SELECT monto, (unix_timestamp(fecha)*1000) AS fecha_timestamp FROM ventas...
to this:
SELECT monto, unix_timestamp(fecha) AS fecha_timestamp FROM ventas...
so you can do the work in php:
$rows[$i]['data'][] = array($r['fecha_timestamp']*1000,$r['monto']);
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have put together a JQuery script that when entering a comment, it goes to a database and pulls the result back and displays it on the page. This works well, however I need a seperate page with just the comments on, which auto refreshes the results every 5 seconds (instead of clicking refresh on the browser). What I would also like is for the comments to FadeIn. I have tried to do this with resources I have found online, but most of them seem to keep replicating my content as well as refreshing.
Can you help?
Comments.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="comments.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Live Comments</title>
</head>
<body>
<div id="leaveComment">
<h2>Leave a Comment</h2>
<div class="row">
<label>Your Name:</label>
<input type="text">
</div>
<div class="row">
<label>Comment:</label>
<textarea cols="10" rows="5"></textarea>
</div>
<button id="add">Add</button>
</div>
<div id="comments">
<h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(function() {
//retrieve comments to display on page
$.getJSON("comments.php?jsoncallback=?", function(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
}
});
//add click handler for button
$("#add").click(function() {
//define ajax config object
var ajaxOpts = {
type: "post",
url: "addComment.php",
data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
success: function(data) {
//create a container for the new comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
$("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");
//empty inputs
$("#leaveComment").find("input").val("");
$("#leaveComment").find("textarea").val("");
}
};
$.ajax(ajaxOpts);
});
});
</script>
</body>
</html>
Moderator.html
<!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>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="comments.css">
</head>
<body>
<div id="comments">
<h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(function() {
//retrieve comments to display on page
$.getJSON("comments.php?jsoncallback=?", function(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
}
});
//add click handler for button
$("#add").click(function() {
//define ajax config object
var ajaxOpts = {
type: "post",
url: "addComment.php",
data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
success: function(data) {
//create a container for the new comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
$("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");
//empty inputs
$("#leaveComment").find("input").val("");
$("#leaveComment").find("textarea").val("");
}
};
$.ajax(ajaxOpts);
});
});
</script>
</body>
</html>
Comments.php
<?php
//db connection detils
$host = "localhost";
$user = "CommentsDB";
$password = "password";
$database = "comments";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT * FROM comments");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);
}
//echo JSON to page
$response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
echo $response;
?>
addComments.php
<?php
//db connection detils
$host = "localhost";
$user = "CommentsDB";
$password = "password";
$database = "comments";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//get POST data
$name = mysql_real_escape_string($_POST["author"]);
$comment = mysql_real_escape_string($_POST["comment"]);
//add new comment to database
mysql_query("INSERT INTO comments VALUES(' $name ',' $comment ')");
?>
QUOTE: auto refreshes the results every 5 seconds
use this code.
function checkForComments() {}
$(document).ready(function () {
//Wait 5 seconds then call checkForComments();
setInterval("checkForComments()", 5000);
});
5000 here is time in milliseconds equivalent to 5 seconds.
QUOTE: but most of them seem to keep replicating my content as well as refreshing.
It isn't clear from your question what exactly does comments.php output. If it outputs all the comments in the database best option would be to keep an array of the ids of the comments that have been posted to page. Just write a function in JavaScript that checks if a particular id exists in that array and append it if it doesn't.
QUOTE: What I would also like is for the comments to FadeIn
follow this question
Making my ajax updated div fade in
UPDATED
JavaScript to load comments
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
//stores the comment IDs
var comments=new Array();
var count=1 ;
function checkForComments() {
$.getJSON("comments.php", addComments);
}
function addComments(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
alert(data[x].id);
if(jQuery.inArray(data[x].id, comments)==-1){
comments[count] = data[x].id;
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
count++;
}
}
}
$(document).ready(function () {
checkForComments();
setInterval("checkForComments()", 5000);
});
</script>
my comments.php
<?php
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT * FROM comments");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
//I have added ID here,
$comments[$x] = array("id" => $row["id"], "name" => $row["name"], "comment"
=> $row["comment"]);
}
echo json_encode($comments);
?>
SQL for comments table
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
)
You have two choices: After adding append()ing the new content, remove the old content.
Or, set a "placeholder" element, and use .html() on it - that way you replace the old content, you don't add more.