good afternoon from gmt+8 timezone.
I had built a login/system , now I want to implement a function that will click out users , so i make a status column in the db ,
2 types of values , lock => lock , active => not lock.
I can use crud method to update the status and output in a table. surely i cam lock the user , and status change to lock, that is working fine, but the problem is the locked user still has access the to system , since the session still valid , she/he has to close the browser or their session is terminated.
on the login page I check if user is lock then can login.
since the user still has access when the session still valid , I want to input ajax call the server to check the status on setInterval.
on backend php: check if user is lock , terminate the session , give alerts box and redirect.
but the issue now is my code is not working, here are my ajax call , if I un-comment //console.log('success');, success will be kept in console.log , meaning the call is success.
<script>
function getUserStatus(){
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
});
}
setInterval(function(){
getUserStatus();
},3000);
</script>
on my ajax.php page , I make sure connection to db is working,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$admin_username = check_input($_POST['username']);
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clicked out');window.location.href='../index.php';</script>";
}
}
function to check user is lock
function isLocked($username){
global $connection ;
$query = "SELECT status FROM table where name = '$username' ";
$result = mysqli_query($connection,$query);
confirm($result);
while( $row = fetch_array($result)){
if($row['status'] == 'locked' ){
return true;
}else{
return false;
}
}
}
if i directly access ajax.php with the log user , below action is working .
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clickedout');window.location.href='../index.php';</script>"; }
not sure what is wrong with my codes and how to fix it ?
any assistance/suggestion would be highly appreciated .
your ajax.php echos something, that may be data, a json or in your case a js script.
The ajax calls ajax/ajax.php, if the http request succeeds it enters
success:
function(response){
//console.log('success');
}
so the variable response holds the output of that call to ajax/ajax.php. if you use
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
dataType: "script",
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
the value of "response" will be executed if it is a working script.(without tags)
further information you can find here:
http://api.jquery.com/jQuery.ajax/
without dataType: "script",in the call you could do something like that:
function(response){
//console.log('success');
$('#somediv').html(response);
}
that will insert the result in a div, if it is a well formated js script, it will be executed.
Related
If user not banned, user can comment here. So I have a php function to check banned user. In case of comment form submitting, a ajax call 1st check this user is banned or not. If not: comment will be submit else display a massage.
Here, I cannot submit any comment if banned or not, Page refresh if I try to submit. In cannot also understand how to apply my banneduser() response to check form submitting.
php function: (I dont want change it, because I used it many more case)
//user name banned by user
function Banned($user){
global $db;
if(!get_magic_quotes_gpc()){
$touser = addslashes($user);
}
$byuser = $_SESSION['user'];
$result = mysqli_query($db,"SELECT * FROM blocking WHERE byname = '$byuser' AND toname = '$touser'") or die(mysqli_error($db));
return (mysqli_num_rows($result) > 0);
}
Ajax:
// check banned user
function banneduser(){
var Bauthor = $("#author").attr("value");
$.ajax({
type: "POST",
url: "../common",
data: "action=Banned&user="+ Bauthor,
success: function(data){
// How to play with this data
if(data){
return false;
}
}
});
return false;
}
//comment submit if user not banned
$(".reply").on("click",function(){
if(banneduser()){
// make form submission
} else { // You are banned}
});
The AJAX request is asynchronous which means the rest of the code (i.e. the return false will execute before the response is processed. This means that banneduser() will always return false.
What you should do is pass a callback function to banneduser which is then executed once the AJAX response is received:
function banneduser(callback){
var Bauthor = $("#author").attr("value");
$.ajax({
type: "POST",
url: "../common",
data: "action=Banned&user="+ Bauthor,
success: function(data){
callback(data)
}
});
return false;
}
//comment submit if user not banned
$(".reply").on("click",function()
{
banneduser(function (is_banned)
{
if (is_banned)
{
// You are banned
}
else
{
// Submit form
}
}
)
});
Although, this script is easily hacked. It's trivial for a visitor (who know what he's doing) to change the value of #author until he finds a value that works. You should use a purely server-side solution to the problem (i.e. a session variable which stores the author value).
I use my own Framework, in localhost all works perfectly fine but not on the server.
I'm logged, so I've a session id.
On a ajax request, the php script doesn't keep my session, if I return the session, the session are empty but me in my side, I keep the session.
It's like if the server thinks the ajax request is a new user.
I don't know where to look and I can't post all the framework code here...
Yesterday I already have this issue (at work) then at home, I retested and all worked great...
I don't get it...
$(document).on('click', '.edit', function(){
$.ajax({
type: "POST",
url: ROOT+"list",
data: {id:id},
headers: {
Accept : "application/json; charset=utf-8"
},
cache: false,
success: function(data){
console.log(data.sess.ROLE);
if(data.status == "error"){
//error
}else{
//ok
}
}
});
});
Controller:
public function editAction(){
//if(!$this->ROLE('tokayn')){ $this->redirectUrl('thread_index'); }
if(Request::POST()){
if(is_int($_POST['id'])){
$user = $this->batiments->findById($_POST['id']);
if($user->id_proprio == $_SESSION['id']){
$data = array('status'=>'ok', 'message'=>$user);
Request::renderJson($data);
}else{
Request::renderJson(array('sess'=>$_SESSION));
//$data = array('status'=>'error', 'message'=>'error');
//Request::renderJson($data);
}
}else{
$data = array('status'=>'error', 'message'=>'error');
Request::renderJson($data);
}
}else{
//$this->redirectUrl('thread_index');
}
}
If a user is not logged, the session role is 'visitor' but if he's logged, the session role is 'connected'.
I've a echo before the ajax form and it's 'connected'.
Then, on submit the ajax form, the ajax request return 'visitor' but if I refresh, I keep the 'connected' echo...
I've faced this issue for me the problem was I was using
https://server:1234/somecontroller
while i was requesting from ajax as
http://server:3344/somecontroller
and session was not shared between https and http so double check if this apply for you.
I have a chatting room with maximum of 2 users, when one user send a message to another, the second user should be notified that new message is received just like Facebook
I have done it with Ajax request like
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
});
}, 1000);
});
<div id="message"></div>
In check_new_msg.php I use the following code:
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
The above code work good but the problem is that it check inbox and new message each second , but it seems harmful for processor as it run a MySQL query each second, please help me how to to execute checking query only when a new message is received.
i will give you a concept then you should try to implement it.
create an external text file when inserting something from another computer and at client side check same file each second rather than checking database. if file exists then check database else continue checking text file
So your only concern is it runs the query every second right?
Here's my solution:
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
What this does is it will call the ajax recursively once the last ajax request is completed.
One of the ways of implementing the feature you discussed is long polling method. In this method you leave the connection open for certain time and if the changes occur within that time, the response is returned back to user. and another connection is opened and so on.
You should google about longpolling as there are lots of tutorials available. Best of luck
I found a good solution for this problem , for this purpose i use a notepad file in same directory where the script exists.
when inserting a new record from any computer you have to create notepad file with insertion.
$insert = mysql_query("insert into inbox .....");
if(insert)
{
if(!file_exists(notepad_file_path))
{
fopen(notepad_file_path);
}
}
Then I call ajax request request
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
After that in external ajax file check existence of notepad file, if file exists then give access to database, in that way it will not be harmful for processor.
if(file_exists(notepad_file_path))
{
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
if(mysql_num_rows($new_msg) == 0)
{
unlink(notepad_file_path);
}
}
i am making a kind of monitor, that shows the changes on database that are created by another web application, i was reloading the page every 10 seconds to show the changes but, i think that is not the "way" to do it, so i was made some research and i found that ajax can do that, calling a function that check that changes, so i wrote my code, but something is missing, so am calling the experts, tha main idea is that when the page are loaded take the id(number) of that last row that was inserted and then saved in a variable called $resultado then call a function called check_changes that do the same query and check the results, if the both variable are equal then no changes, if they are different the reload page.
monitor.php
<head>
<script type="text/javascript" src="./js/prototype.js"></script>
<script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script>
</head>
<?
//code that makes and print the query.
// here i check the last id(number) and saved on $resultado variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=db_query($qry0,$conn);
while($row=$qry1->fetch_array())
{
$resultado=$row['id'];
}
//here i call check_changes every 30 seconds
echo "<script>setTimeout('check_changes()',30);";
//ajax function that check the status of database
echo "function check_changes(){
$.ajax({
type: 'POST',
data: {'data':$resultado}, //here am sending the value of result via post
url: './checker.php', //to checker.php
success: function(data) {
if(data.result==true){
window.location = window.location.pathname;
}
}
})
}";
echo "</script>";
?>
checker.php
<?
$result4 = $_POST['data'];
include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
$dbc=connect_db("seguridad");
// here i check the last id(number) and saved on $result3 variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=$dbc->query($qry0);
while($row=$qry1->fetch_array())
{
$result3=$row['id'];
}
//here i check if both are equal send false to monitor.php
if ($result4==$result3){
$result=false
echo json_encode($result);
}
else {
// a new row has been inserted, send true to monitor.php an reload page
$result=true
echo json_encode($result);
}
?>
<script type="text/javascript">
var pollTimeout;
var observeChange = {
'poll' : function() {
$.ajax({
type: "POST",
url: 'checker.php',
data:"data=<?php echo $resultado; ?>",
dataType:"json",
async:true,
success:function(response){
// we have success fully received response,clear the timeout
clearTimeout(pollTimeout);
observeChange.update(response);
},
error: function(XMLHttpRequest,textStatus){
//some error has occured please try after 5 seconds
pollTimeout = setTimeout(function()
{
observeChange.poll();
}, 1000);
}
});
},
'update' : function(json) {
//check whether change is there from serever or not if yes than reload page else do poll request again
if(json.changed=="yes"){
window.location.reload();
}
else{
observeChange.poll();
}
}
};
$(document).ready(function(){
observeChange.poll();
});
</script>
you can easily do it via comet,it is not advisable to query server for every 10 seconds,you should increase timeout on apache server if you are using apache
suggested apache configurations are
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 240
MaxClients 150
MaxRequestsPerChild 4
checker.php
<?
$result4 = $_POST['data'];
$response=array("changed"=>"no");
include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
$dbc=connect_db("seguridad");
// here i check the last id(number) and saved on $result3 variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=$dbc->query($qry0);
while($row=$qry1->fetch_array())
{
$result3=$row['id'];
}
if ($result4==$result3){
$response['changed']="yes";
}
echo json_encode($response); exit;
?>
You are missing some semicolons in your php-code. I don't think it works at all. You should check for php error messages generated in your postback script.
In your javascript you are comparing the result to a boolean value. The data returned will be a string. This is the correct way, notice the single quotes.
if(data.result=='true'){
window.location = window.location.pathname;
}
in checker.php you are sending data after converting into JSON format ,
but in ajax request you haven't defined the datatype at all,
also if the data coming at ajax success is JSON then you have to parse it first..
$.ajax({
type: "GET",
url: 'checker.php',
data:{'ata:$resultado},
dataType:"json",
success:function(data){
if( JSON.parseQuery(data)) //this will run if the result is true.
{
window.location = window.location.pathname;
}
}
});
NOTE:
I gave up on trying to do the processing in one go, and just let it return after every x number of sends.
Two paths,
/sms?action=send
/sms?action=status
Let's say that the send path starts sending 10,000 sms messages via REST api calls.
I make a call to that page via ajax.
Then every few seconds, I make a call to /sms?action=status to see how the progress is going, and to update a progress bar.
The status path returns false if no messages are being sent.
What ends up happening is that the ajax call to the SEND path gets the ajax success: function called almost instantly, even though I know the script is taking 1+ minute to complete execution.
My progress bar never gets shown because the status ajax call (which is in a set interval with a few second delay) never seems to actually get called until the send call completes.
I'm trying to put the relevant code in here, but it may not be as clear as it should be without all the context.
<script type="text/javascript">
var smsInterval = 0;
var smsSending = false;
$(document).ready(function() {
var charCount = 0;
var smsText = "";
var smsTotal = <?php echo $options["smsTotal"]; ?>;
<?php if($options["sending"]): ?>
smsStatus();
smsSending = true;
smsInterval = setInterval("smsStatus()", 5000);
<?php endif; ?>
$("span#smsadmin_charcount").html(charCount.toString());
//send button
$("div#smssend").click(function() {
if(smsSending == true) {
return false;
}
smsStatus();
var dataString = $("#smsadmin_form").serialize();
smsSending = true;
$("div#smssend").html("Sending...");
$.ajax({
type: "POST",
url: "<?php echo $base_url; ?>/admin/sms",
data : dataString,
success: function(data) {
},
error: function(request, error) {
$("div.notice.sms").html("ERROR "+error+ "REQUEST "+request);
}
});
});
});
function smsStatus() {
var dataString = "smsaction=status&ajax=true";
$.ajax({
type: "POST",
url: "<?php echo $base_url; ?>/admin/sms",
data : dataString,
success: function(data) {
//data being false here indicates the process finished
if(data == false) {
clearInterval(smsInterval);
var basewidth = $("div.sms_progress_bg").width();
$("div.sms_progress_bar").width(parseInt(basewidth));
$("div.sms_progress_notice").html(parseInt(100) + "% Complete");
smsSending = false;
$("div#smssend").html("Send To <?php echo $options["smsTotal"]; ?> Recipients");
} else {
var pcomplete = parseFloat(data);
$("div.sms_progress_bg").show();
var basewidth = $("div.sms_progress_bg").width();
$("div.sms_progress_bar").width(parseInt(basewidth * pcomplete));
$("div.sms_progress_notice").html(parseInt(pcomplete * 100) + "% Complete");
}
},
error: function(request, error) {
$("div.notice.sms").html("ERROR "+error+ "REQUEST "+request);
}
});
}
I might be missing the point, but inside the $("div#smssend").click you got this line:
smsStatus();
shouldn't it be:
smsInterval = setInterval("smsStatus()", 5000);
and INSIDE the success: function(data) for /admin/sms ?
If the send part is sending out 10k messages, and the status returns true if currently sending a message, and false if in between sending, then you have a design issue.
For example, what is status supposed to be showing?
If status is to show how many of a certain block have been sent, then what you can do is to submit the message to be sent (or addresses), and get back some id for that block.
Then, when you ask for a status, pass the id, and your server can determine how many of that group has been sent, and return back the number that were successful, and unsuccessful, and how many are still pending. If you want to get fancy, you can also give an indication how much longer it may be before finishing, based on how many other requests are also pending.
But, how you approach this really depends on what you expect when you ask for the status.