Layout, Phonegap and JSON - javascript

I have an application to list the information via JSON db, I can list the information from db, the problem is that it comes without the layout of jQuery Mobile, could someone give me some light on how to solve this problem?
Below is my code:
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Unidas Taxi</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" charset="utf-8" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.mobile-1.4.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.mobile-1.4.3.css"/>
<script charset="utf−8" type="text/javascript">
var id_taxista = 1;
setInterval(function(){
//alert('oi');
corridas();
}, 3000);
$("#result").html("");
function corridas(){
$.post('url', {
'id_taxista': id_taxista
}, function (data) {
$("#result").html(data);
});
}
</script>
</head>
<body>
<div data-role="page" id="main">
<div data-role="header">
<h1>Unidas Taxi</h1>
</div>
<div id="content" data-role="content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Corridas <span class="ui-li-count">2</span></li>
<span id="result">
</span>
</ul>
</div>
</div>
</body>
</html>
PHP:
$server = "localhost";
$username = "username";
$password = "pass";
$database = "db";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id_taxista = $_POST["id_taxista"];
$sql = "SELECT USED";
if (mysql_query($sql, $con)) {
$query = mysql_query($sql) or die(mysql_error());
$html = '';
while($row = mysql_fetch_assoc($query)){
$html .= '<li id="'.$row['id_corrida'].'">
<a href="index.html">
<h2>'.$row['nome'].' '.$row['sobrenome'].'</h2>
<p><strong>Hotal Ibis - Botafogo</strong></p>
<p>Quarto: 504, Tel.: (21) 0932-0920</p>
<p class="ui-li-aside"><strong>'.$row['data'].' '.$row['hora'].'</strong></p>
</a>
</li>';
}
echo $html;
} else {
die('Error: ' . mysql_error());
}
mysql_close($con);

If I understand your question correctly, you are able to return json full of data you want and display it in #result but the style doesn't have the jQuery Mobile style applied. If this is a correct summation
First, add an id to your listview element
<ul id="mylistview" data-role="listview" data-inset="true">
then add this line after $("#result").html(data);
$( "#mylistview" ).listview( "refresh" );
See the Listview Widget page for more on listviews.

Related

How can I change my code so that the user can only like the post once?

I want to make a like system and this is what I have so far. I can't figure out how to make it only increment once can anyone help me out? I feel like i might have to use session variables but im not sure.
index.php
<?php
$con = mysqli_connect('localhost', 'root', '','phplikes');
$query = "SELECT * FROM meme_vote ORDER BY vote DESC";
$res = mysqli_query($con, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Voting System</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<?php while($row = mysqli_fetch_assoc($res)){ $location = $row['video_location'];?>
<div class="col-md-4">
<div class="post">
<h4 class="post-title"><?php echo $row['title']?></h4>
<div id="postdesign">
<video src="<?php echo $row['video_location'] ?>" width="100%" height="240" controls></video>
</div>
<a href="javascript:void(0)" class="btn btn-info btn-lg">
<span class="glyphicon glyphicon-thumbs-up " onclick="like_update('<?php echo $row['id']?>')">Vote
(<span id="like_loop_<?php echo $row['id']?>"><?php echo $row['vote']?></span>)
</span>
</a>
</div>
</div>
<?php }?>
</div>
</div>
<script>
function like_update(id){
var cur_count = jQuery('#like_loop_'+id).html();
cur_count++
jQuery('#like_loop_'+id).html(cur_count);
jQuery.ajax({
url:'update_count.php',
type:'post',
data:'type=like&id='+id,
success:function(result){
}
})
}
</script>
</body>
</html>
update_count.php
<?php
$con = mysqli_connect('localhost', 'root', '', 'phplikes');
$type = $_POST['type'];
$id = $_POST['id'];
if($type=='like'){
$sql = "update meme_vote set vote=vote+1 where id=$id";
$sql2 = "update meme_vote set fake_vote=fake_vote+1 where id=$id";
}
$res = mysqli_query($con, $sql);
$res2 = mysqli_query($con, $sql2);
?>
Also just to let you know, I already have session variables established ie. $_SESSION['user_id'] and `$_SESSION['username']
Since you already have a user_id, I'll assume you have a users table.
You could create a new table with meme_vote_id and user_id columns, and a unique index using both fields:
CREATE TABLE `meme_voters` (
`meme_vote_id` INT UNSIGNED NOT NULL,
`user_id` INT UNSIGNED NOT NULL,
UNIQUE INDEX `unique_voter` (`meme_vote_id`, `user_id`)
);
Then when someone votes:
$sql = mysqli_query($con,"SELECT COUNT(*) AS count FROM meme_voters WHERE meme_vote_id={$id} AND user_id={$_SESSION['user_id']}" );
$rs = mysqli_fetch_object($sql);
if ( $rs->count == 0 ) {
$sql = "INSERT INTO meme_voters (meme_vote_id, user_id) VALUES ({$id}, {$_SESSION['user_id']})";
mysqli_query($con, $sql);
$sql = "UPDATE meme_vote SET vote=vote+1 WHERE id=$id";
$res = mysqli_query($con, $sql);
}

JS/HTML/PHP in one PHP program and MYSQL Updates via Server Sent Events

I'm building a two-way chat application that stores messages into a MySQL database. I would like to use Server Sent Events and have the PHP and HTML all in one page but the problem I'm facing is that the header cannot be set to text/event-stream or I will break the HTML.
My question is how can I have the PHP, JS and HTML on the same page when using Server Sent Events?
Here is my opening JS. I set the EventSource to index.php even though this might be wrong.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index.php");
source.onmessage = function(event) {
document.getElementsByClassName("message").innerHTML = event.data;
};
}else {
document.getElementsByClassName("message").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream");
}
else {
header("Content-Type: text/html");
}
//Database Stuff
$connect = mysqli_connect('localhost', 'user', 'Pass');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
?>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<?php echo "data: ".$row['mymessages']; flush();?>
</div>
</div>
<?php
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
?>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<?php echo "data: ".$row['yourmessages']; flush();?>
</div>
</div>
<?php
}
}
?>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
EDIT: I have tried separating the PHP the HTML and put the PHP logical part outside the HTML. I'm able to get Server Sent Events via inspector in Chrome but not sure how to loop through the DB entries in JS. I'm not comfortable with JS syntax.
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
if(isset($_POST['submit'])){
$send = $_POST['mymessage'];
$sendmsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('".$send."', '')";
}
if (!empty($_GET['yourmessage'])){
$recieve = $_GET['yourmessage'];
$recievemsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('', '".$recieve."')";
}
$connect = mysqli_connect('localhost', 'root', 'Walcott34');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$sqlrecieve = mysqli_query($connect, $recievemsg);
$sqlsend = mysqli_query($connect, $sendmsg);
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
echo "data: ".$row['mymessages']."\n\n";
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
echo "data: ".$row['yourmessages']."\n\n";
}
ob_flush();
flush();
}
}
else {
?>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index2.php");
source.onmessage = function(e){
document.getElementById("mymessages").innerHTML = event.data;
document.getElementById("yourmessages").innerHTML = event.data;
};
}else {
document.getElementsById('message').innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<div id='mymessage'>
</div>
</div>
</div>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<div id='yourmessage'>
</div>
</div>
</div>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
<?php } ?>
If your after it being in one file you just need the one outer if statement which separates the two logical parts.
<?php
if ($_SERVER["HTTP_ACCEPT"] === 'text/event-stream') {
// event stream code
...
while (true) {
...
} else {
// client side code
?>
<head>
<meta name="viewport" content="w
...
<?php }
You cant intertwine the two parts like your doing:
<div class='message'>
<?php echo "data: $row['mymessages']"; flush();?>
</div>
Your serverside part is incomplete but that's beyond the scope of the question,ive commented with a link to a working example.

using ajax call to empty the div

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

how do i make each query collapse php

I have this PHP and jQuery code which works in coalition with my database. This is the only page. The code runs and gives me a row of data, but when I click the collapse button it only works for the first row. Even if I click any other row, that action affects only the first row and all the other rows collapse, which is useless.
How do I make it so that all rows work? It's like the button is doubled and only works for the first row.
<script>
$(function() {
$('div#dl_box').on('show', function(e) {
console.log('show', $(e.target).attr('class'), $(e.target).attr('id'));
$(e.target).prev('.accordion-heading').addClass('active');
});
$('div#dl_box').on('hidden', function(e) {
console.log('hidden', $(e.target).attr('class'), $(e.target).attr('id'));
$(e.target).prev('.accordion-heading').removeClass('active');
});
});
$(document).ready(function() {});
</script>
<?php
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', ''));
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . 'db'));
$query = "SELECT * FROM AS_Questions";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if (!$result) {
printf("Errormessage: %s\n", $mysqli->error);
}
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "
<section class='section swatch-white editable-swatch'>
<div class='container'>
<div class='panel panel-primary panel-ws-download'>
<div class='panel-heading'>
<a href='#group_accordion_stable' class='accordion-toggle collapsed' data-parent='#accordion_download' data-toggle='collapse'>
" . $row['Question'] . "
</a>
</div>
<div id='group_accordion_stable' class='panel-collapse collapse' style='height: 0px;'>
<div class='panel-body'>
<!-- first -->
<ul class='list-unstyled list-ws-download'>
<li>" . $row['Answer'] . "</li>
</ul>
</div>
</div>
</div>
</div>
</section>
"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); //Make sure to close out the database connection
?>
sample for u.
<!DOCTYPE html>
<html>
<head>
<style>
.default {
display: block;
background: pink;
height: 3em;
width: 10em;
transition: height 5s, background 3s; /*collaspe speed*/
margin-top: 1em;
}
.expanded {
height: 10em;
background: yellow;
transition: height 1s, background 2s; /*expand speed*/
/*display: none;*/
}
</style>
</head>
<body>
<?php
$i = 0;
while ($i <5) {
$i++;
echo '<div class="default" id="ChangeThisId_'.$i.'">';
echo '
<a href="#"
name="ChangeThisId_'.$i.'"
onclick="changeHeight(this.name)">
Click me '. $i .'
</a>
';
echo '</div>';
}
// above return in html.
// <div class="default" id="ChangeThisId_1">
// CLick me 1
// </div>
// <div class="default" id="ChangeThisId_2">
// Click me 2
// and so on till ...5
?>
</body>
<script>
function changeHeight(x){
//alert(x); //x return name of clicked <a> tag.
document.getElementById(x).classList.toggle("expanded");
}
</script>
</html>
This is using css, html(+php to create row), and native javascript.
The idea is to assign an unique for each row.
others are quite self explanatory, hope this helps.
to anyone coming in here in search of sql data display with accordian collapse. here Qid is my tables auto incremented value. AS_Questions is my table name. db is my database name.
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<?php
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', 'password')); //The Blank string is the password
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . 'db'));
$query = "SELECT * FROM AS_Questions";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if (!$result) {
printf("Errormessage: %s\n", $mysqli->error);
}
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "
<div class='panel-group' id='accordion'> <!-- accordion 1 -->
<div class='panel panel-primary'>
<div class='panel-heading'> <!-- panel-heading -->
<h4 class='panel-title'> <!-- title 1 -->
<a data-toggle='collapse' data-parent='#accordion' href='#accordion" . $row['Qid'] . "'>
" . $row['Question'] . " <i class='fa fa-eye' style='float: right;'></i>
</a>
</h4>
</div>
<!-- panel body -->
<div id='accordion" . $row['Qid'] . "' class='panel-collapse collapse'>
<div class='panel-body'>
" . $row['Answer'] . "
</div>
</div>
</div>
"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); //Make sure to close out the database connection
?>
<?php
$con = mysqli_connect("localhost", "root", "", "student_data")
?>
<!doctype html>
<html lang="en">
<head>
<title>Colapse</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<?php
$count = 0;
$fetch = mysqli_query($con, "SELECT * FROM student_cs");
if (mysqli_num_rows($fetch) > 0) {
while ($record = mysqli_fetch_assoc($fetch)) {
$count++;
?>
<div class="col-4">
<p>
<button <?php $count; ?> class="btn btn-primary mt-3" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
<h5> <?php echo $record['s_name']; ?> </h5>
</button>
</p>
<div class="collapse" id="collapseExample">
<div class="card card-body">
<h3> <?php echo $record['id']; ?> </h3>
<h4> <?php echo $record['s_name']; ?> </h4>
<h5> <?php echo $record['rollnumber']; ?> </h5>
<h6> <?php echo $record['class']; ?> </h6>
</div>
</div>
</div>
<?php }
}
?>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

php - Session Not Carrying Over but Variables Are

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

Categories

Resources