adding a php variable to a jquery url - javascript

please friends i want to run a javascript code to load a php page which is based on $_GET variable. here is the actual page:
<?php
$online = mysqli_query($con, "SELECT * FROM (SELECT user as user FROM online) as a INNER JOIN
(SELECT one as f1 FROM friends WHERE two='$my_id'
UNION SELECT two as f2 FROM friends WHERE one='$my_id') as b
ON a.user = b.f1");
while($query = mysqli_fetch_array($online)){
$active = $query['user'];
$first = getuser($active, 'first');
$nick = getuser($active, 'nick');
$last = getuser($active, 'last');
?>
<?php
echo "<font class='driver'>$first $nick $last</font>";
<div style="width:100%;height:82%;overflow-x:no;overflow-y:auto;" id="show">
<script type="text/javascript" src="jscript.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('active_chat.php')
}, 2000);
});
</script>
</div>
so i want this line $('#show').load('active_chat.php') to look something like this $('#show').load('active_chat.php?id=$active') so that it will display information entered by only a user for each $active, here is the active_chat.php;
<?php
include 'connect.php';
include 'functions.php';
$my_id = $_SESSION['user_id'];
$user = $_GET['id'];
$query = mysqli_query($con, "SELECT * FROM all_msgs WHERE (my_id='$my_id' AND user_id='$user') OR (my_id='$user' AND user_id='$my_id') AND delet !='$my_id' ORDER BY id DESC");
while($sql = mysqli_fetch_array($query)){
$msg = $sql['msg_body'];
$sender = $sql['my_id'];
$first = getuser($sender, 'first');
$nick = getuser($sender, 'nick');
$last = getuser($sender, 'last');
$photo = getuser($sender, 'photo');
echo $first." ".$nick." ".$last;
} ?>

Related

Javascript output online usernames in HTML table

I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
$query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
$query->execute();
$query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
$query->execute();
}
function addOrRefresh($ID){
$query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
$count = $query->fetchColumn();
if($count == 0){
$query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
$query->bindParam(':ID', $ID);
$query->execute();
}
else{
$query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
removeRefresh();
$ID = $_GET['id'];
addOrRefresh($ID);
$query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
$query->execute();
$onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
$resultaat = "";
foreach($onlineUsers as $user){
$resultaat .= "<p>{$user['username']} <br></p>";
}
echo "$resultaat";
}
?>
You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
<?php
session_start();
$ID = $_SESSION['ID'];
if (isset($_POST['logout'])) {
session_destroy();
$query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
?>
<html>
<head>
<title>Stratego</title>
<Link href="../layout/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./js/HeartBeat.js"></script>
<script>
$(document).ready(function () {
heartbeat.setSpelerId( <?php echo $ID; ?> );
heartbeat.polling();
});
</script>
</head>
<body>
<form method='post' name='logout' action="../setup/logout.php">
<input type='submit' name='loggout' value='Log me out'>
</form>
Singleplayer
<div id="online-list">
</div>
</body>
<?php echo "<script>
function heartbeat(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById(\"online-list\").innerHTML = xhttp.responseText;
}
};
xhttp.open(\"GET\", \"./wachtruimterInterface.php?action=heartbeat&id=" . $ID . "\", true);
console.log('keeping in touch ༼つ ◕_◕ ༽つ');
xhttp.send();
}
setInterval(heartbeat, 1000);
</script>"; ?>
</html>
The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
$resultaat .= "<tr><td>{$user['username']} <br></td></tr>";
}
echo "<table>$resultaat</table>";
Just now, doesn't seem to work, any tips on how to progress?
I've fixed the issue;
$resultaat = "";
foreach($onlineUsers as $user){
$naam= $user['username']
$resultaat .= "<tr><td>$naam</td></tr>";
}
echo "<table border=1>$resultaat</table>";

How to use buttons in html to keep language the user chooses in php session

I have multiple PHP files and need to use session_start() to keep track of the website language. There are two buttons ENG and GRE the default language assigned to $_SESSION['lang'] is ENG. When the user clicks on Greek the $_SESSION['lang'] needs to be updated and all the databases contents that are in Greek need to be displayed.
functions.php
<?php
include "connection.php";
session_start();
function getLang(){
if (isset($_GET['lang'])){
return $lang = $_GET['lang'];
}
else{
return $lang='ENG';
}
}
function getValue($name,$connection){
$lang = getLang();
$query = "SELECT Text FROM users WHERE Nickname='$name' AND Lang='$lang'";
$result = mysqli_query($connection, $query);
$text = mysqli_fetch_assoc($result);
return checkText($text['Text'],$name,$connection);
}
function checkText($text,$name,$connection){
if ($text==null){
$sql = "SELECT Text FROM users WHERE Nickname='$name' AND Lang='Eng'";
$result = mysqli_query($connection,$sql);
$text = mysqli_fetch_assoc($result);
return $text['Text'];
}
else{
return $text;
}
}
function getPk($name,$connection){
$lang = getLang();
$query = "SELECT id FROM users WHERE Nickname='$name' AND Lang='$lang'";
$result = mysqli_query($connection,$query);
$text = mysqli_fetch_assoc($result);
return $text['id'];
}
index.php
<?php include "functions.php";
session_start();
$_SESSION['lang'] = 'ENG';
?>
This is were I start the session.
<script>
$(document).ready(function(){
$('.lang').on('click',function(){
var lang = $(this).attr('id');
});
});
</script>
<script>
var pks = [];
var nicks = [];
$(document).ready(function(){
$('#bt').on('click',function(){
$('.to_edit').each(function(){
var a = $(this).attr('data-pk');
var nick = $(this).attr('data-name');
$(this).wrapInner("<a class='edit1'></a>");
$('.edit1').attr('data-type','text');
pks.push(a);
nicks.push(nick);
});
var i=0;
$('.edit1').each(function() {
$(this).attr('data-pk', pks[i]);
$(this).attr('data-name',nicks[i]);
i++;
});
$.fn.editable.defaults.mode='inline';
var options = {};
options.url = 'update.php';
$('.edit1').editable(options);
});
});
</script>
The first script is what I've written so far for the buttons that have the ENG and GRE writings and the second is inline editing with x-editable.
Here are the buttons:
<button class="lang" id="En">ENG</button>
<button class="lang" id="Gr">GRE</button>
My questions are how to obtain the id of the buttons which is ENG and GRE, how to update $_SESSION[lang'], will I need to use session_start() in all files?
Use session_start() right at the beginning of connection.php or functions.php as some of them you should always include in every file you have.
<?php
session_start();
$servername = "localhost";
$username = "root";
..
In the same file you have included in every other file, add the condition if the language has changed:
if(!isset($_SESSION['lang'])) { $_SESSION['lang'] = 'ENG'; }
if(isset($_GET['lang'])) {
$_SESSION['lang'] = $_GET['lang'];
}

cant fillter characters in jcombo

Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.

Jquery Refresh Not Refreshing Right

So I have a basic php page and it calls another php page that contains my mysql query and output. Pretty simple. I am using a jquery refresh statement below to auto refresh the div that the query is in:
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#records').load('user_records.php').fadeIn("slow");
}, 30000); // refresh every 30 seconds
</script>
Here is my user_records.php file:
<?php
$username = $_GET['user'];
include('connect.php');
$did = array();
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$user_id = $row['id'];
}
$sql = "SELECT * FROM assign_did WHERE user_id = '$user_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$did_id = $row['did_id'];
$sql1 = "SELECT did FROM did WHERE id = '$did_id'";
$result1 = mysqli_query($link, $sql1, MYSQLI_STORE_RESULT);
while($row1 = $result1->fetch_row()){
$did[] = $row1[0];
}
}
$did_arr = array();
foreach($did as $newdid){
$did_arr[] = '`extension` LIKE \'%'.$newdid.'\'';
}
echo "<div id='records'><h1 align='center'>Today's Transfers</h1>
<table cellspacing='0' cellpadding='0'>
<tr>
<th> Customer Name</th><th>Phone Number</th><th>Disposition</th><th>DID</th><th>Date Called</th>
</tr>
";
$sql3 = 'SELECT * FROM `vicidial_did_log` WHERE ('.implode(" OR ", $did_arr) . ')';
$result3 = mysqli_query($link, $sql3, MYSQLI_STORE_RESULT);
while($row3 = $result3->fetch_assoc()){
$caller_id_number = $row3['caller_id_number'];
$extension = $row3['extension'];
...echo the rows into rows and columns...
?>
So it refreshes user_records.php that has a div with id 'records'. That div performs the mysql query and echos is. My problem is that when it does the refresh, the query just goes blank. It refreshes the div, because I have a few things that echo/output before the query starts and starts outputting. Not sure what I am doing wrong here or what code you guys need to see. I hope someone can help. Thank you.

Why is this jQuery autocomplete not working?

I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Categories