I've writen this code but it doesn't work. I'm pretty sure it's mostly correct, but I don't know what's wrong with it. The script returns as output "undefined"
------PHP ON SERVER----------------- (http://www.autofficinacicco.it/json.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli($nomehost, $nomeuser, $password, "");
$result = $conn->query("SELECT codice, immagine, testo FROM Promozioni");
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[]=$rs;
}
$conn->close();
echo json_encode($outp);
?>
-----JAVA SCRIPT----------------------------------------
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.autofficinacicco.it/json.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out+=arr["immagine"];
out+="</br>";
out+=arr["codice"];
out+="</br>";
out+=arr["testo"];
out+="</br>";
}
out += "</table>"
document.getElementById("id").innerHTML =out;
}
</script>
Your JSON is not proper document. Change json formating and use json_encode(); function
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Codice":"' . $rs["codice"] . '",';
$outp .= '"Testo":"' . $rs["testo"] . '",';
$outp .= '"Immagine":"'. $rs["immagine"] . '"}';
}
$outp .="]";
$conn->close();
to
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[] = $rs;
}
$conn->close();
echo json_encode($outp);
Related
I keep having this error. I manage to track down the response by inspecting the dataTable which lead me to believe that this is the source of the problem. Please bear with me for I'm still a beginner in javascript and PHP.
image link to error:
source of error
here are my codes:
config.php
<?php
class dbConfig {
protected $serverName;
protected $userName;
protected $password;
protected $dbName;
function dbConfig() {
$this -> serverName = 'localhost';
$this -> userName = 'root';
$this -> password = '';
$this -> dbName = 'database';
}
}
?>
user.php
<?php
require('config.php');
class User extends dbconfig {
protected $hostName;
protected $userName;
protected $password;
protected $dbName;
private $userTable = 'user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$database = new dbConfig();
$this -> hostName = $database -> serverName;
$this -> userName = $database -> userName;
$this -> password = $database -> password;
$this -> dbName = $database -> dbName;
$conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else{
$this->dbConnect = $conn;
}
}
}
private function getData($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
private function getNumRows($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$numRows = mysqli_num_rows($result);
return $numRows;
}
public function userList(){
$query = "SELECT * FROM ".$this->userTable." ";
if(!empty($_POST["search"]["value"])){
$query .= 'where(user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$result = mysqli_query($this->dbConnect, $query);
$numRows = mysqli_num_rows($result);
$userData = array();
while ($user = mysqli_fetch_assoc($result)) {
$userRows = array();
$userRows[] = $user['user_id'];
$userRows[] = ucfirst($user['user_fname']);
$userRows[] = $user['user_mname'];
$userRows[] = $user['user_lname'];
$userRows[] = $user['user_address'];
$userRows[] = $user['user_contactnumber'];
$userRows[] = $user['user_birthdate'];
$userRows[] = '>button type="button" name="update" id="'.$user['user_id'].'"class="btn btn-warning btn-xs update"<Update>/button<';
$userRows[] = '>button type="button" name="delete" id="'.$user['user_id'].'"class="btn btn-danger btn-xs update"<Delete>/button<';
$userData[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $userData
);
echo json_encode($output);
}
}
?>
ajax.js
$(document).ready(function(){
var userRecords = $('#userList').DataTable({
"lengthChange": false,
"processing": true,
"serverSide": true,
"order":[],
"ajax":{
url:"process.php",
type: "POST",
data: {action: 'listUser'},
dataType: "json"
},
"columnDefs":[
{
"targets": [0, 6, 7],
"orderable": false,
},
],
"pageLength": 10
});
});
process.php
<?php
include('user.php');
$user = new User();
if (!empty($_POST['action']) && $_POST['action'] == 'listUser') {
$user -> userList();
}
?>
I am trying to sort data that pulls with an ajax get request, how do i get all the checked categories instead of only the one pressed, would be nice to get both 2/3 if both are checked?
Currently I insert a number in the database under "kategori" and they should be sorted through these numbers?
how do i get both queries in the url?
Example here : http://xch07.wi2.sde.dk/sandbox/SQL/
HTML
<form>
<input class="kategorier" type="checkbox" value="1">Kat 1<br>
<input class="kategorier" type="checkbox" value="2">Kat 2 <br>
<input class="kategorier" type="checkbox" value="3">Kat 3
</form>
<br>
<div id="txtHint">Person info will be listed here...
</div>
JS/AJAX
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(let i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
showUser(this.value);
});
};
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","index.php?page=getuser&kategori="+str ,true);
xmlhttp.send();
}
}
PHP
$kategori = intval($_GET['kategori']);
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori = $kategori ";
$result = $dbCon->query($sql);
echo "<table>
<tr>
<th>Id</th>
<th>Navn</th>
<th>Efternavn</th>
<th>email</th>
<th>Kategori</th>
</tr>";
while($row = $result->fetch_object()) {
$id = $row->id;
$navn = $row->navn;
$efternavn = $row->efternavn;
$email = $row->email;
$kategori = $row->kategori;
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $navn . "</td>";
echo "<td>" . $efternavn . "</td>";
echo "<td>" . $email . "</td>";
echo "<td>" . $kategori . "</td>";
echo "</tr>";
}
echo "</table>";
<script type="text/javascript">
window.onload = function () {
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(var i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
var checked = '';
for (var k = 0; k < kategorierLength; k++) {
if (checked) {
var separator = ',';
} else {
var separator = '';
}
if (kategorier[k].checked) {
checked += separator+kategorier[k].value;
}
}
alert(checked);
if (checked) {
showUser(checked);
}
});
}
}
After that you need to change your query and use IN statement like below.
$kategori = $_GET['kategori'];
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori IN ($kategori)";
$result = $dbCon->query($sql);
I was wondering how I could pull a table from a database I already have set up. I have my own code, but it won't work out. The objective is for the person to click on a button that runs a JavaScript function that runs a PHP file and then displays it on website in a specific div I have for it. If anybody can help me figure out what is wrong that would be awesome! Here is the code:
Kataajax.js
tkakata(){
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlHttp)
alert("Something went wrong")
else
return xmlHttp
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
xmlHttp.open("GET", "tkakatagrab.php", true)
xmlHttp.onreadystatechange = handleServerResponse();
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("displayrank").innerHTML = message;
setTimeout('process()',1000);
}
else
{
alert("Database not connecting!")
}
}
}
}
tkakatagrab.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$con = mysqli_connect('IP','username','password','TKACONT');
if(!$con){
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT Firstname,Lastname,Kata FROM Contestant ORDER BY Kata DESC";
$result = mysqli_query($con,$sql);
echo '<response>';
echo "<table>
<tr>
<th>Points</th>
<th>Firstname</th>
<th>Lastname</th>";
//while loop right here
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Kata'] . "</td>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo '</response>';
mysqli_close($con);
?>
I have this class for a megamenu used in a category menu for an ecommerce web application.
class categories {
var $categorie;
var $tabs;
var $subcategorie;
var $website;
var $coloane = 3;
var $randuri = 10;
function tabs(){
global $pdoconnect;
$stmt = $pdoconnect->query("SELECT * FROM taburi WHERE vizibil = '1' ORDER BY ordine ASC");
$tabs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tabs_c = $stmt->rowCount();
$return = "";
if($tabs_c > 0){
$i = 1;
$return .= "\n<ul class=\"tabs\">\n";
foreach($tabs as $t){
$return .= "\t<li class=\"level0\">\n";
$return .= "\t\t<div class=\"tab-title\">\n";
$return .= "\t\t\t<span class=\"tab-image\">\n";
$return .= "\t\t\t\t".'<img src="'.$this->website.'/media/taburi/'.$t['logo'].'" />'."\n";
$return .= "\t\t\t</span>\n";
$return .= $t['nume'];
$return .= "\t\t</div>\n";
$return .= "\t".'<div class="level1 hmm-megamenu-box">'."\n";
$return .= $this->categorie($t['id']);
$return .= "\t</div>\n";
$return .= "\t</li>\n";
}
$return .= "</ul>";
}
return $return;
}
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
if($categorie_c > 0){
$i = 0;
$return .= "<div class=\"hmm-megamenu-block\">\n";
foreach ($categorie as $cat) {
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
// if($i % 2 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
// $return .= "</div><div class=\"hmm-megamenu-column\">\n";
// }
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$return .= "\t\t</div>\n";
$i++;
}
$return .= "</div>";
}
return $return;
}
function subcategorie($cat){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE categorie=:categorie AND subcategorie IS NOT NULL");
$stmt->bindValue(':categorie', $cat, PDO::PARAM_STR);
$stmt->execute();
$subcategorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$subcategorie_c = $stmt->rowCount();
if($subcategorie_c > 0){
foreach ($subcategorie as $scat) {
$return .= "\t".''.$scat['subcategorie'].''."\n";
}
}
return $return;
}
}
For the moment the menu items looks like this
but the desired result should be
How can i get this result just with php?
I suspect the problem is two fold, in both style and HTML markup.
From a style perspective, your current layout is more or less a grid. You need something a lot more fluid within your CSS.
To allow this, you might need to pre-calculate columns so that you know you're evenly distributing X groups with a total of Y items into 3 columns. This lets you deal with cases where one group may have more items than can fit in the height of the menu (and need to overflow).
Solved
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
$return .= "<div class=\"hmm-megamenu-block\">\n";
if($categorie_c > 0){
$i = 1;
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
foreach ($categorie as $cat) {
if($i % 3 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 3 == 0 && !empty($i) && $this->countCategorii($tab) >= $this->coloane){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 2== 0 && $this->countCategorii($tab) == 2){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$i++;
}
$return .= "</div>";
}
$return .= "</div>";
return $return;
}
I populated a list using the following code.
I'm trying to make each of the objects retrieved from the server act like a button and when clicked throw a pop up box displaying address, date, and status. Is there anyway to do this? I've been looking into using Ajax but it is getting a little confusing as I have an html file and a php file that has all my javascript/php (the javascript relies on a php function) and from what I've read I would need to make another php file to service the request. How then would I reference it within my html file to do so? I may be making this harder than it needs to be.
Original Code:
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
switch($row["status"]){
case 3:
echo '<div id= "content" style = "background-color: red" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 4:
echo '<div id= "content" style = "background-color: yellow" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 5:
echo '<div id= "content" style = "background-color: green" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
}
}
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
$row = $result->fetch_assoc();
$temp[] = $row;
$db_connection->close();
return json_encode($temp);
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function popinformation(data){
var json = <?php getalerts(); ?>
console.log(json);
}
Update:
Here's what I was trying, from what I've read I have a misunderstanding of php/javascript. This is all my code within the file. Colors appear fine but pop-ups do not appear, Console reports Uncaught SyntaxError: Unexpected token < which will go away if I delete the final script. I think that means the error is within the echo json_encode($results) somehow.
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
My html Document
<html>
<head>
<link rel="stylesheet" href="css/logged_in.css">
<?php
include("login_php_scripts.php");
?>
</head>
<body>
<div id="navigation">
Account
Logout
</div>
<div id="header">
<div id="logo"></div>
<div id="header_text"></div>
</div>
<div id="content_wrapper">
<div id="list_view">
I am logged in as: <?php echo $_SESSION['user_name']; ?></br>
<?php
getwarnings();
?>
</div>
<div id="map">
<script>
createmap();
</script>
</div>
</div>
<div id="footer"></div>
</body>
</html>
Put all the database results into an array, then convert that to a Javascript object that your popup function can look up by ID.
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
?>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
</script>
<?php
}