Hey Im having an issue in accessing the variable from JQuery Ajax. I ve tried everything. I even added cdn script tag to both files. but I keep getting this error of undefined index
Notice: Undefined index: head in C:\xampp\htdocs\Project\View.php on line 20
Anyone has any idea wats wrong with the syntax. I have attached both my files below.
SearchProjects.php
<html>
<head>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#assign tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
$('td').on('click',function() {
var heading=$(this).text();
alert(heading);
$.ajax({
url: "View.php",
type: "POST",
data: {head: heading},
success: function(data){
alert("success");
}
});
});
</script>
</head>
<body>
<div>
<div class="col-md-12"><br/></div>
<?php
session_start();
$No="Not Assigned";
require("DB.php");
$query="SELECT `ID`, `Assigned_By`, `name`, `path`, `heading`,`Assigned_to`, `Completed`, `Date`, `Due_Date`, `Price` FROM `assign` where `Assigned_to`='Not Assigned' order by Date Desc";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
echo "<table class=table table-hover id=assign>"
."<thead>"
. "<tr> "
. "<th>ID</th>"
. "<th>Assigned_By</th>"
. "<th>Name</th>"
. "<th>Path</th>"
. "<th>Heading</th>"
. "<th>Assigned_To</th>"
. "<th>Completed</th>"
. "<th>Due_Date</th>"
. "<th>Submission_Date</th>"
. "<th>Price</th>"
. "</tr> </thead> ";
while($row = $result->fetch_assoc()) {
echo "<tr>"
. "<td>".$row["ID"]."</td>"
. "<td>".$row["Assigned_By"]."</td>"
. "<td>".$row['name']."</td>"
. "<td>".$row['path']."</td>"
. "<td>".$row['heading']."</td>"
. "<td>".$row['Assigned_to']."</td>"
. "<td>".$row['Completed']."</td>"
. "<td>".$row['Date']."</td>"
. "<td>".$row['Due_Date']."</td>"
. "<td>".$row['Price']."</td>"
. "<td><a class=btn btn-default href=View.php role=button>Show More!</a></td>"
. "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
?>
</div>
</body>
View.php
<html>
<head>
<title>TODO supply a title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<?php
session_start();
if(isset($_POST['head'])){
echo $_POST['head'];
}
$filename="CV.docx";
// $filename=$_SESSION['filename'];
//echo $filename."<br/>";
require("DB.php");
$query="SELECT `heading` FROM `assign` where `name`='$filename'";
$result=mysqli_query($PDB,$query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$heading=$row['heading'];
$_SESSION['heading']=$heading;
}
}
else {
echo "0 results";
}
$dir = "Assigns/";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if(!($file=="." || $file=="..")){
$f=explode(".",$file);
if(strcmp($f[0],$heading)){
if(!file_exists("Assigns/$file")) {
die("File not found");
}
else{
$my_file = "Assigns/$file";
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
}
}
}
}
closedir($dh);
}
}
if($_SERVER['REQUEST_METHOD']== 'POST'){
if (isset($_POST['save'])) {
$assigned_to=$_SESSION['username'];
echo $assigned_to;
echo $filename;
$query="UPDATE `assign` SET `Assigned_to`='$assigned_to' WHERE `name`='$filename'";
$result=mysqli_query($PDB,$query);
if($result){
echo "wohooo";
}
else{
echo "nooo";
}
}
else if (isset($_POST['submit'])) {
// echo "submit";
header('location: Solution.php');
}
}
?>
<div class="container">
<form action="View.php" method="post">
<h1 style="clear:both;"><?php echo $heading."<br/>" ?> </h1>
<div class="form-group">
<?php echo $data; ?>
</div>
<div class="col-md-12 col-md-offset-6">
<input type="submit" name="submit" value="Submit Solution">
<input type="submit" name="save" value="Save Changes">
</div>
</form>
</div>
</body>
Always check the existence of a variable/array index before using it:
$head = isset($_POST['head']) ? $_POST['head'] : null;
//may check nullity of $head
There seem to be two things going on: First of all, the click handler for the td is not attached because the DOM was not ready, wrap your jQuery code in
$(function() {
//your code
})
Also, the click event on the tr and on the td are both fired...
Related
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.
I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
Been working on this for long time.. want to add a js effect (hide/unhide) to a simple submit form...
Fortunately it is working but unfortunately it is only working for single row in the DB table.
I made script:1 (posted below) which was corrected by a well wisher from this site which is script:2 (posted below).
unfortunately both are not working. hope you guys help me find the missing peice in it..
SCRIPT#1
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$servername = "localhost";
$password = "*****";
$dbname = "the_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
?>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<style>
.name {
width: 700px;
margin-top: 1%;
margin-left: 20%;
padding-left:2%;
padding-right:2%;
padding-top:10%;
margin-right: 35%;
word-wrap: break-word;
}
textarea#addtext{
width:600px;
height:100px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$().ready = function() {
$('#addtext').hide();
$('#addsubmit').hide();
$("#add").click(function() {
$('#add').hide();
$('#addtext').fadeIn('slow').focus();
$('#addsubmit').fadeIn('slow');
});
$('#addtext').blur(function(){
$('#addtext').hide();
$('#addsubmit').hide();
$('#add').fadeIn('slow');
});
}();
});//]]>
</script>
</head>
<body>
<div class="name">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { ?>
<div id="q">
<B><big><font color= #ba4a00> Q:</font></big> <?php echo $row["question"]; ?> </B></br>
<B><small><font color= #ba4a00> Description:</font> <?php echo $row["description"]; ?> </small></B></br>
<p id="tag1"><small> <?php echo $row["subject"]; ?> </small></p><p id="tag2"><small> <?php echo $row["sub_subject"]; ?> </small></p>
<button class="addanswer" id="add"><B>Add Answer</B></button>
<form>
<textarea class="addtext" name="addtext" required id="addtext" placeholder="Please type your question here.."></textarea>
<button class="addanswer" id="addsubmit"><B>Submit</B></button>
</form>
<small><p><?php echo $row["date"]; ?></p></small>
</div>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</body>
</html>
SCRIPT#2
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "the_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
?>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<style>
.name {
width: 700px;
margin-top: 1%;
margin-left: 20%;
padding-left:2%;
padding-right:2%;
padding-top:10%;
margin-right: 35%;
word-wrap: break-word;
}
textarea#addtext{
width:600px;
height:100px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
<script type='text/javascript'>
function addanswer(index){
$('#add_' + index).hide();
$('#addtext_' + index).fadeIn('slow').focus();
$('#addsubmit_' + index).fadeIn('slow');
}
</script>
</head>
<body>
<div class="name">
<?php
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++; // stuff inside foreach goes here
?>
<div id="q">
<B><big><font color= #ba4a00> Q:</font></big> <?php echo $row["question"]; ?> </B></br>
<B><small><font color= #ba4a00> Description:</font> <?php echo $row["description"]; ?> </small></B></br>
<p id="tag1"><small> <?php echo $row["subject"]; ?> </small></p><p id="tag2"><small> <?php echo $row["sub_subject"]; ?> </small></p>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea style="display:none;" type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your question here.."></textarea>';
echo '<button style="display:none;" onClick="addsubmit('.$index.');" type="addsubmit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
<small><p><?php echo $row["date"]; ?></p></small>
</div>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</body>
</html>
Any Help would be greatly Appreciated..
Ok so here is your code rewritten, I have not tested it but it should work if your PHP code has no syntax error and your DB is up and running:
config.php (I added config.php as its just better practice)
<?php
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "the_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
list.php (this will be your template file and some php logic in there *not the best practice)
<?php require_once('config.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<style>
.name {
width: 700px;
margin-top: 1%;
margin-left: 20%;
padding-left: 2%;
padding-right: 2%;
padding-top: 10%;
margin-right: 35%;
word-wrap: break-word;
}
textarea#addtext {
width: 600px;
height: 100px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
</head>
<body>
<div class="name">
<?php
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++; // stuff inside foreach goes here
?>
<div id="q">
<!-- NEVER user an ID on elements that are recurring, thats completely wrong, use a class or 'data-' attr -->
<B><big><font color= #ba4a00> Q:</font></big> <?php echo $row["question"]; ?> </B>
</br>
<B><small><font color= #ba4a00> Description:</font> <?php echo $row["description"]; ?> </small></B>
</br>
<p id="tag1"><small> <?php echo $row["subject"]; ?> </small></p>
<p id="tag2"><small> <?php echo $row["sub_subject"]; ?> </small></p>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your question here.."></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
<small><p><?php echo $row["date"]; ?></p></small>
</div>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.add').click(function(e) {
e.preventDefault();
$(this).parent().find('form').fadeIn('slow').focus();
$(this).hide();
});
});
</script>
</body>
</html>
Second Edit
If you need to hide the form when the textarea is out of focus:
https://api.jquery.com/focusout/
$('.addtext').focusout(function() {
$(this).parent().fadeOut('slow');
$(this).parent().parent().find('.add').show();
});
** Third Edit **
Auto Focus on the textarea specifically
<script type='text/javascript'>
$(document).ready(function() {
$('.add').click(function(e) {
e.preventDefault();
$(this).parent().find('form').fadeIn('slow');
$(this).parent().find('form textarea.addtext').focus();
$(this).hide();
});
});
</script>
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.
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.