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;
}
}
});
Related
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.
This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:
I am quite new to jQuery and AJAX.
I am sending the request via AJAX to check file 'test' every 5 seconds which works fine. 'test' stands for test.php file.
<script>
$(document).ready(function () {
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
dataType: "html", //expect html to be returned
contentType: "text/html",
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
// $("#display").click(load); //if you want to start the display on click
});
</script>
<div id="responsecontainer"></div>
test.php
$id = $this->session->userdata('UserID');
$get_friends_notification = $this->friends_model->get_friends_alert_by_ID($id);
if(isset($get_friends_notification) && !empty($get_friends_notification))
{
?>
<div id="test" style="width:200px; height:auto; border:1px solid red;">
<h3>Friend invitation from:</h3>
<?php
foreach($get_friends_notification as $key => $value)
{
$new_id = $get_friends_notification[$key] = $value["FrieInviter"];
$new_name = $get_friends_notification[$key] = $value["UserName"];
echo ''.$new_name.'<br />';
}
?>
</div>
<?php
}
Then it just displays it in the div # responsecontainer which works fine too.
$("#responsecontainer").html(response);
In the file 'test' I am checking database if there were any updates.
So I am pulling the information from DB and return to #responsecontainer. As it runs every 5 seconds, after it ran for the first time I would like to grab the last ID that I pulled and before it runs again and save it in variable and then I would like to pass that ID to the 'test' or process it differently. Basically I want to be able to use it. How can I do that??
EXAMPLE:
ajax checks test.php file and find 5 rows. returns these 5 rows with 5 IDs. The last ID is number 5. In the meantime there were some other rows inserted so next time it will find more rows.
Before it checkes again I want to tell it to not to check ID 1,2,3,4,5 but start from ID 6.
Also how does this method works with DB connections? Assuming that I have for example 500 users, and on all of theirs profiles that check would run every 5 seconds wouldnt it kill database connections?
Basically you need to add a pgination effect in here. Pass a parameter in the ajax request for example : if you are getting 5 records at a time,
then initialize a variable say
current_page = 0 , increment the same as you request via ajax
var current_page=0;
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
data : current_page
dataType: "html", //expect html to be returned
contentType: "text/html",
success: function (response) {
if(response.length!==0){
$("#responsecontainer").html(response);
current_page+=1;
}
setTimeout(load, 5000)
}
});
}
in the php page make the necessary changes (hope you know how pagination is done).
I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.
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.