How to refresh a page section using ajax/json? - javascript

i am building a chat website, now i working on ONLINE USER.
I use AJAX to refresh but i meet some problems with Append.();.
When refreshing section the same data appear again and again...That is the PHP file.
<?php
public function online(){
$database = new DB();
$db = $database->database();
$array = array();
$ref = $_SESSION['oc_users_ref'];
$time_out = time()-5;
$time = time();
$query = $db->query("SELECT * FROM oc_users WHERE users_online = 0");
$updateOnline = $db->query("UPDATE oc_users SET users_online = 1 WHERE users_lastcome < '$time_out'");
$q = $db->query("SELECT * FROM oc_users WHERE users_ref <> '$ref' AND users_online = 0 ORDER BY users_lastcome DESC");
while($data = $q->fetch()) {
if($data['users_online'] == 1){
$class = "opacity30";
}else{
$class = '';
}
$array[] = $data;
}
print json_encode($array);
} ?>
Now the Javascript
function getOnline(){
$.ajax({
url: "conf/users.php?act=online",
dataType: "text",
success: function(data) {
var json = $.parseJSON(data);
for (var i=0;i<json.length;++i)
{
$('#printOnline').append('<li><a href="javascript:void(0);" onclick=javascript:chatWith("'+json[i].users_nickname+'")><i></i>'+json[i].users_nickname+'</a></li>');
}
}
});
}
setInterval('getOnline()',10000);
And the result*
User001
User001
User001
User001
User001
User001
User001
User001
Please help me...Great Thanks

Reset the user list before updating:
function getOnline(){
$.ajax({
url: "conf/users.php?act=online",
dataType: "text",
success: function(data) {
$('#printOnline').html("");
var json = $.parseJSON(data);
for (var i=0;i<json.length;++i)
{
$('#printOnline').append('<li><a href="javascript:void(0);" onclick=javascript:chatWith("'+json[i].users_nickname+'")><i></i>'+json[i].users_nickname+'</a></li>');
}
}
});
}
setInterval('getOnline()',10000);

Related

JSON_encode not outputting anything

I want to send a query result from one php file to my javascript, I've used an AJAX which seems to work as it is getting data from my BaseClass.php. However when using JSON_encode, it is not outputting anything at all. So I can't work out how to send a query result from one php file(MySQLDao.php) to my BaseClass.php so I am then able to send it to my Javascript file.
My Code:
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode("param" .$param);
echo json_encode("body" .$body);
echo json_encode("recieved" .$recieved);
echo json_encode("result" .$result);
exit();
}
?>
output for the above echo statements:
"paramgetResults""body""recieved""result"
MySQLDao.php - this file holds the query result that I want to pass to my js
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
// echo($obj);
// return $obj;
//}
echo json_encode($result);
//echo($result);
//return false;
}
}
?>
My AJAX code in my js file:
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
Any help is appreciated thanks!

PHP, phpmyadmin, html, javascript

I am having an issue ordering into a table primary id values which auto-increment from phpmyadmin and adding them into a table from recent to latest (greatest to lowest) can i get some help? I am using json to get php to javascript. This code only shows the table from latest to recent.
$app->get('/proyects/all', function () use($servername, $dbname, $dbuser, $dbpassword)
{
$response = array();
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbuser, $dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM proyectos");
if ($stmt->execute()) {
$result = $stmt->fetchAll();
}
$conn = null;
if(!empty($result))
{
$response['proyects'] = array();
foreach ($result as $key => $value)
{
$response['proyects'][$key] = $value;
}
$response['success'] = true;
echo json_encode($response);
return;
}
else
{
$response['success'] = false;
$response['message'] = "Proyects not found";
echo json_encode($response);
return;
}
}
catch(PDOException $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
echo json_encode($response);
return;
}
});
<script type="text/javascript">
$(document).ready(function()
{
$.ajax(
{
url: path+'/proyects/all',
type: 'get',
dataType: "json",
success: function(json)
{
console.log(json);
if (json.success)
{
$.each(json.proyects, function( index, value ) {
$('#proyecs').append('<tr><td>'+value.idproyect+'</td><td>'+value.pdescription+'</td><td>'+value.presponsible+'</td><td>'+value.pdateini+'</td><td>'+value.pdatefin+'</td><td>'+value.pstatus+'&#37</td><td><button type="button" class="btn btn-default">Details</button></td></tr>');
});
}
else
{
Materialize.toast(json.message, 5000, 'red accent-4');
}
},
error : function(e, settings, exception)
{
Materialize.toast("Oops! an error has ocurred", 5000, 'red accent-4');
}
});
});
</script>
#sesonrario #rex sorry forgot the code
Could
$stmt = $conn->prepare("SELECT * FROM proyectos order by id");
solve your problem?

commands in chatroom & defining words after command

Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.

Undefined Index Issue and Error return

Marked as fixed!!!
I was missing vat_rate in my MySQL business database. This was causing both issues. Thanks Nytrix and Grimbode both for the swift and walk through support, much appreciated! :)
I'm getting an undefined index issue on line 16...
<?php
class Business extends Application {
private $_table = 'business';
public function getBusiness() {
$sql = "SELECT * FROM `{$this->_table}`
WHERE `id` = 1";
return $this->db->fetchOne($sql);
}
public function getVatRate() {
$business = $this->getBusiness();
return $business['vat_rate'];
}
}
How can I fix it? Thanks.
Also, I'm getting an error pop-up when I click my add to basket and remove from basket links, which is called from basket.js on line 13 and 14. I don't know how to fix that either, but think it may have something to do with the above?
Regards
Edit; Thinking I've done a var_dump correctly(?), this is what is shown for $business when I wrote
<?php var_dump($business); ?>
in my _header.php file to echo the array (I say that though with no knowledge!).
Notice: Undefined variable: business in /Users/ashleysmith/Documents/Website Tests/Z - Work from this/ecommerce/template/_header.php on line 68
NULL
Here's all the relevant code as far as I know...
Business.php
<?php
class Business extends Application {
private $_table = 'business';
public function getBusiness() {
$sql = "SELECT * FROM `{$this->_table}`
WHERE `id` = 1";
return $this->db->fetchOne($sql);
}
public function getVatRate() {
$business = $this->getBusiness();
return $business['vat_rate'];
}
}
basket_small_refresh.php
<?php
require_once("../inc/autoload.php");
$objBasket = new Basket();
$out = array();
$out['bl_ti'] = $objBasket->_number_of_items;
$out['bl_st'] = number_format($objBasket->_sub_total, 2);
$out['bl_vat'] = number_format($objBasket->_vat, 2);
$out['bl_total'] = number_format($objBasket->_total, 2);
echo json_encode($out);
basket_left.php
<div id="small_basket">
<?php $objBasket = new Basket(); ?>
<p class="your_bas">Your Basket</p>
<dl id="basket_left">
<dt>No. of items:</dt>
<dd class="bl_ti"><span><?php echo $objBasket->_number_of_items; ?></span></dd>
<dt>Sub-total:</dt>
<dd class="bl_st">£<span><?php echo number_format($objBasket->_sub_total, 2); ?></span></dd>
<dt>VAT (<span><?php echo $objBasket->_vat_rate; ?></span>%):</dt>
<dd class="bl_vat">£<span><?php echo number_format($objBasket->_vat, 2); ?></span></dd>
<dt>Total (inc):</dt>
<dd class="bl_total">£<span><?php echo number_format($objBasket->_total, 2); ?></span></dd>
</dl>
<p class="check_button">
View Basket |
Checkout
</p>
</div>
basket.php
<?php
require_once('../inc/autoload.php');
if (isset($_POST['job']) && isset($_POST['id'])) {
$out = array();
$job = $_POST['job'];
$id = $_POST['id'];
$objCatalogue = new Catalogue();
$product = $objCatalogue->getProduct($id);
if (!empty($product)) {
switch($job) {
case 0:
Session::removeItem($id);
$out['job'] = 1;
break;
case 1:
Session::setItem($id);
$out['job'] = 0;
break;
}
echo json_encode($out);
}
}
Basket.php
<?php
class Basket {
public $_inst_catalogue;
public $_empty_basket;
public $_vat_rate;
public $_number_of_items;
public $_sub_total;
public $_vat;
public $_total;
public function __construct() {
$this->_inst_catalogue = new Catalogue();
$this->_empty_basket = empty($_SESSION['basket']) ? true : false;
$objBusiness = new Business();
$this->_vat_rate = $objBusiness->getVatRate();
$this->noItems();
$this->subtotal();
$this->vat();
$this->total();
}
public function noItems() {
$value = 0;
if (!$this->_empty_basket) {
foreach($_SESSION['basket'] as $key => $basket) {
$value += $basket['qty'];
}
}
$this->_number_of_items = $value;
}
public function subtotal() {
$value = 0;
if (!$this->_empty_basket) {
foreach($_SESSION['basket'] as $key => $basket) {
$product = $this->_inst_catalogue->getProduct($key);
$value += ($basket['qty'] * $product['price']);
}
}
$this->_sub_total = round($value, 2);
}
public function vat() {
$value = 0;
if (!$this->_empty_basket) {
$value = ($this->_vat_rate * ($this->_sub_total / 100));
}
$this->_vat = round($value, 2);
}
public function total() {
$this->_total = round(($this->_sub_total + $this->_vat), 2);
}
public static function activeButton($sess_id) {
if(isset($_SESSION['basket'][$sess_id])) {
$id = 0;
$label = "Remove From Basket";
} else {
$id = 1;
$label = "Add To Basket";
}
$out = "<a href=\"#\" class=\"add_to_basket";
$out .= $id == 0 ? " red" : null;
$out .= "\" rel=\"";
$out .= $sess_id."_".$id;
$out .= "\">{$label}</a>";
return $out;
}
}
basket.js
$(document).ready(function() {
function refreshSmallBasket() {
$.ajax({
url: '/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("Error occured");
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove From Basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add To Basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("Error occured");
}
});
return false;
});
}
});
Ok, so you are selecting everything * from you're table defined as $_table = "business". You want to select the 'vat_rate' column that may not exists in the returnd array. Here for you checked with var_dump how you're array looks. If you want to know how to select a value from that array please look on the documentation: http://php.net/manual/en/language.types.array.php OR http://www.w3schools.com/php/php_arrays.asp (mabey a bit simpler explained)
Marked as fixed!!!
I was missing vat_rate in my MySQL business database. This was causing both issues. Thanks Nytrix and Grimbode both for the swift and walk through support, much appreciated! :)

update values in the textboxes using javascript

actualy im just a newbie programmer and i made my own update javascript function for my program but sadly the codes doesnt update..can anyone help me assist in order my codes work? please.
i want to do is if i change the values in the textboxes and click update it will update.
script:
<script type="text/javascript">
$(document).ready(function() {
$('#updates').click(function() {
$id1 = $('#id1').val();
$di2 = $('#id2').val();
$name1 = $('#name1').val();
$name2 = $('#name2').val();
$optA1 = $('#optA1').val();
$optA2 = $('#optA2').val();
$optB1 = $('#optB1').val();
$optB2 = $('#optB2').val();
$other_qual1 = $('#other_qual1').val();
$other_qual2 = $('#other_qual2').val();
$interview1 = $('#interview1').val();
$interview2 = $('#interview2').val();
$total1 = $('#total1').val();
$total2 = $('#total2').val();
$.ajax({
type: "POST",
cache: false,
url: "update.php",
data: "id1_text="+$name1,
data: "id2_text="+$name1,
data: "name1_text="+$name1,
data: "name2_text="+$name2,
data: "optA1_text="+$optA1,
data: "optA2_text="+$optA2,
data: "optB1_text="+$optB1,
data: "optB2_text="+$optB2,
data: "other_qual1_text="+$other_qual1,
data: "other_qual2_text="+$other_qual2,
data: "interview1_text="+$interview1,
data: "interview2_text="+$interview2,
data: "total1_text="+$total1,
data: "total2_text="+$total2,
success: function(data) {
alert('data has been updated!');
}
});
});
});
</script>
update.php code:
<?php
mysql_connect("localhost","root","") or die ("cant connect to database!");
mysql_select_db("test") or die ("cant find database!");
$id1=$_POST['id1_text'];
$id2=$_POST['id2_text'];
$name1=$_POST['name1_text'];
$name2=$_POST['name2_text'];
$optA1=$_POST['optA1_text'];
$optA2=$_POST['optA2_text'];
$optB1=$_POST['optB1_text'];
$optB2=$_POST['optB2_text'];
$other_qual1=$_POST['other_qual1_text'];
$other_qual2=$_POST['other_qual2_text'];
$interview1=$_POST['interview1_text'];
$interview2=$_POST['interview2_text'];
$total1=$_POST['total1_text'];
$total2=$_POST['total2_text'];
$query1=mysql_query("UPDATE score SET name='$name1', score1='$optA1', score2='optB1', other_qual='$other_qual1', interview='$interview1', total='$total1' WHERE id='$id1'");
$resource1 = mysql_query($query1)
or die (mysql_error());
$query2=mysql_query("UPDATE score SET name='$name2', score1='$optA2', score2='optB2', other_qual='$other_qual2', interview='$interview2', total='$total2' WHERE id='$id2'");
$resource2 = mysql_query($query2)
or die (mysql_error());
?>
You had quite a few errors in your code. For example, you had a wrong syntax when you assigned data in the JS-code. It should be in this form:
data: { val:$("#selector").val, val2:$("#selector2").val(), /* etc etc*/ }
Solution
Try this code:
JS
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var id1 = $('#id1').val();
var id2 = $('#id2').val();
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var optA1 = $('#optA1').val();
var optA2 = $('#optA2').val();
var optB1 = $('#optB1').val();
var optB2 = $('#optB2').val();
var other_qual1 = $('#other_qual1').val();
var other_qual2 = $('#other_qual2').val();
var interview1 = $('#interview1').val();
var interview2 = $('#interview2').val();
var total1 = $('#total1').val();
var total2 = $('#total2').val();
$.ajax({
type: "POST",
cache: false,
url: "update.php",
data: {
id1_text: name1,
id2_text: name1,
name1_text: name1,
name2_text: name2,
optA1_text: optA1,
optA2_text: optA2,
optB1_text: optB1,
optB2_text: optB2,
other_qual1_text: other_qual1,
other_qual2_text: other_qual2,
interview1_text: interview1,
interview2_text: interview2,
total1_text: total1,
total2_text: total2
},
success: function (data) {
alert('data has been updated!');
}
});
});
});
</script>
PHP
<?php
if (isset($_POST['id1_text'])) {
mysql_connect("localhost", "root", "") or die("cant connect to database!");
mysql_select_db("test") or die("cant find database!");
$id1 = $_POST['id1_text'];
$id2 = $_POST['id2_text'];
$name1 = $_POST['name1_text'];
$name2 = $_POST['name2_text'];
$optA1 = $_POST['optA1_text'];
$optA2 = $_POST['optA2_text'];
$optB1 = $_POST['optB1_text'];
$optB2 = $_POST['optB2_text'];
$other_qual1 = $_POST['other_qual1_text'];
$other_qual2 = $_POST['other_qual2_text'];
$interview1 = $_POST['interview1_text'];
$interview2 = $_POST['interview2_text'];
$total1 = $_POST['total1_text'];
$total2 = $_POST['total2_text'];
$query1 = mysql_query("UPDATE score SET name=$name1, score1=$optA1, score2=$optB1, other_qual=$other_qual1, interview=$interview1, total=$total1 WHERE id=$id1");
$resource1 = mysql_query($query1) or die(mysql_error());
$query2 = mysql_query("UPDATE score SET name=$name2, score1=$optA2, score2=optB2, other_qual=$other_qual2, interview=$interview2, total=$total2 WHERE id=$id2");
$resource2 = mysql_query($query2) or die(mysql_error());
}
?>

Categories

Resources