In my Dashboard.php I call an Ajax Request every 800ms that fetches data from a php file and changes the inner html of an element on my Dashboard.php.
I use it to display a 60 seconds coundown since last activity. Once it reaches 0 it should send the user to logout.php and from there to index.php.
The problem now is that I stay on my page and index.php gets inserted into my div. How can I force it to a site refresh?
Dashboard.php
<script type="text/javascript">
setInterval(function(){
getSessionEnd();
}, 800);
</script>
app.js
var st = document.getElementById("sessiontime");
if (typeof(st) != 'undefined' && st != null){
sessionEnds();
}
function getSessionEnd() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sessiontime").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./assets/ajax/sessionEnds.php");
xhttp.send();
}
SessionEnds.php
<?php
session_start();
require_once '../../includes/datacon.php';
global $pdo;
$sql = $pdo->prepare('SELECT * FROM userdata JOIN user ON user.id = userdata.uid WHERE username=?');
$sql->bindParam(1, $_SESSION['user']);
$sql->execute();
$sqlu = $sql->fetch( );
$timeS = strtotime($sqlu['lastseen']);
$timeE = strtotime(date("Y-m-d H:i:s", strtotime("+". 1 . " minutes", $timeS)));
$timeD = $timeE - time();
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%i minutes and %s seconds');
}
$timeD = secondsToTime($timeD);
if($timeE < time()){
Header('Location: ../../includes/logout.php');
exit();
} else {
echo $timeD;
}
?>
change to
if($timeE < time()){
echo "0"; // send 0 response
} else {
echo $timeD;// send time
}
also
if (this.readyState == 4 && this.status == 200) {
if (this.responseText=="0" || this.responseText==" 0"){
window.location("logout.php");// got to logout page
}
else
document.getElementById("sessiontime").innerHTML = this.responseText;
}
Change the code as this
give the correct path to logout page..
You need to go to the logout page from the current page in browser.
PHP is server side and you'd like to force the client to reload, so, it looks like you need to add something in jscript to force the client to refresh the page, like changing the window.location, or location.reload
window.location=<your target>
//or
location.reload()
To add in logout.php I presume.
Related
I am creating a website with a login system for a university assignment. the method to do this i have created is have a a php page (the main page) have a section on the top that checks for a session variable for the user:
<?php
// open the session
session_start();
header('Access-Control-Allow-Origin: *');
// check for existing user
if(isset($_SESSION['User'])){
$isUser = true;
$userName = $_SESSION['userName'];
}else{
$isUser = false;
}
?}
There is more to this but the rest is just functions that use the session to add appropriate fields (login section/logged in confirmation) this works fine.
In order to change the session variable a login confirmation function is used (very long script to check against database, also works perfectly) and at the end of the login check if correct changes the session variable like so:
//Start the session
session_start();
$arrUser = $result[0];
$_SESSION['User'] = $arrUser[0];
$_SESSION['userName'] = $arrUser[1];
return true;
this works, if loaded in a separate page (changes the session variable and adjusts adjusts the page to confirm session has changed, only if url in manually opened with variables). however by attempting to run the php using ajax:
function Login(){
var Username = document.getElementById("Username");
var Password = document.getElementById("Password");
if(Username.value != "" && Password.value != ""){
URL = "https://localhost/CAB230/Login.php?username=" + Username.value +
"&password=" + Password.value;
httpGetAsync(URL, function(response){
if(response){
location.reload();
} else {
document.getElementById("Username").style.background = "red";
document.getElementById("Password").style.background = "red";
}
});
} else {
window.alert("Username and Password fields must both be filled out");
}
}
function httpGetAsync(theUrl, callback){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
results in true being return and the page being reloaded, but the session variable don't change as the login section loads instead of the logged in confirmation section.
This is very confusing because running this ajax on my laptop changes the session variable, however on my PC this doesn't work.
Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}
I've hit a brick wall in my chat system project and I have tried all day to find a solution. So here I am.
In the file insert.php I am trying to use $_REQUEST to get the value of the textarea from chat.php.
When I type something in and click send, a blank message is sent to the database.
After playing around with it, sometimes the webpage displays a "1" in the div element im trying to display the message in.
Any help would be very much appreciated thank you.
chat.php
<!DOCTYPE html>
<html>
<head>
<title>{ Chat App }</title>
<link rel = "stylesheet" href = "styles/style.css" media = "all" />
<script src="insert.js"></script>
<link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
</head>
<body>
<form name = "form1">
<textarea name = "message"></textarea>
<br>
Send
<br>
<div id = "msg"></div>
</form>
</body>
</html>
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
insert.php
<?php
include("connection/connection.php");
global $con;
$msg = isset($_REQUEST['msg']);
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
$get_msg = "SELECT * FROM msg ORDER by id DESC";
$run_msg = mysqli_query($con, $get_msg);
while($row = mysqli_fetch_array($run_msg)){
echo $row['message'];
}
?>
The first problem is when you check for the null value, the function continues and submits the form if it is null or not.
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
// stop the submit action
return;
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
The next problem is in the form handler, you are saving a boolean value isset($_REQUEST['msg']). Try this
insert.php
...
$msg = (isset($_REQUEST['msg']) && !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : false;
if($msg){
// save data to database
...
}
or
...
if((isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
// message was submitted and it is not an empty string
$msg = $_REQUEST['msg'];
// save data to database
...
}else{
// do nothing
}
xmlhttp.open('GET', 'insert.php', true); try changing to xmlhttp.open('GET', 'insert.php?msg='+msg, true);
Hope it helps !
better to add "return" on error when you check if message is empty
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
so it could be
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
return;
}
in submit() function
so the rest of function will not execute and empty message won't be sent.
and assign to variable message not the validation ))
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
$msg = $_REQUEST['msg']; //addiotionally this need escape
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
}
I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}
My code makes an xmlhttp request to a php file, sending an ID so that a record can be identified and deleted from the database. However, when performing the delete query, I'm get an error saying 'comicID' is undefined (the variable using the ID value sent by POST). I'm not sure how to make sure it is defined correctly. Currently, the error I'm getting back from error handling is: "No comic supplied." and the error I get when removing the ISSET section of code is: "Error. Pages in comic not deleted." As it stands, the delete query doesn't work.
Javascript:
function delComic()
{
var radioButtons = $("#listID input:radio[name='comicList']");
var radioID = radioButtons.index(radioButtons.filter(':checked'));
console.log(radioID);
if (radioID < 0)
{
window.alert("You must select a comic before deleting.");
}
else
{
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php?comicID="+radioID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
}
PHP:
<?php
if (isset($_POST["comicID"]))
{
$comic = $_POST["comicID"];
$dir = 'comics/'.$comic.'/';
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
include_once('includes/conn.inc.php');
mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
$query = ("DELETE FROM page WHERE comicID = '$comic'");
if (!$result = mysqli_query($conn, $query))
{
echo ("Query1 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
$dirHandle = opendir($dir);
while($file = readdir($dirHandle))
{
if(!is_dir($file))
{
unlink("$dir"."$file");
}
}
closedir($dirHandle);
rmdir($dir);
$query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
if (!mysqli_query($conn, $query2))
{
echo ("Query2 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
echo ("The selected comic was successfully deleted.");
}
else
{
echo ("Error. Comic not deleted.");
}
}
}
else
{
echo "Error. Pages in comic not deleted.";
}
}
$conn->close();
}
else
{
$comic = null;
echo "No comic supplied";
}
?>
With POST you do your Ajax request different that with GET. The query string is an argument to the send() function rather than part of the url, and you leave off the ?:
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);
Edit:
You also really should urlencode the parameter values, if they can contain spaces, etc. And to circumvent possible browser caching you can add a parameter with the time:
var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());
There's no need to read that timestamp param on the server-side; its only to trick the browser.
Change the three first lines to, and everything should work fine.
if (isset($_GET["comicID"]))
{
$comic = $_GET["comicID"];
I actually solved it myself by accident. It turns out the error is that the program is halting at the point that it tries to delete all pages associated with a comic. When it is presented with an already empty comic, it tries to delete nonexistent records. Manually adding a page to the comic and THEN trying to delete the comic outright worked perfectly.
So basically, I just need error handling for empty comics.
Thanks for the pointers regarding POST, however.