I have a web application that use notification to inform user about anything new (just like Facebook).
My solution is that I send a request every three seconds to check the database if there is anything new to display (jQuery and AJAX). However, this makes the application slow, since a request is sent to check tables every three seconds.
I want to know how to make these notifications work without interrupting the application.
So this is my JS code:
jQuery(document).ready(function(){
LoopNotificationCRM();
});
function LoopNotificationCRM(){
setTimeout('LoopNotificationCRM();',3000);
$.ajax({
async: false,
type: "POST",
url: "controllers/c_ajax_notification.php",
data: "ordre=check_new_notification",
success: function(msg){
if(msg != 'NAN'){
var t = msg.split('***');
$('.sNotification').html(t[0]);
$('.ul-notification').html(t[1]);
$('.alert-notification').css('display','block');
}else{
$('.sNotification').html(0);
$('.alert-notification').css('display','none');
$('.ul-notification').html('');
}
},
error: function (xhr, status) {
alert('Erreur: ' + status);
}
});
}
And this is my PHP Code:
$notification->getNewNotification("*");
if($notification->db_num_row != 0){
$listNoti = '';
while($resN = $notification->fetch_array()){
$today = new DateTime(date('Y-m-d H:i:s'));
$datNoti = new DateTime($resN['date_not_crm']);
$diff = $datNoti->diff($today);
if($diff->d == 0){
if($diff->h == 0){
if($diff->i == 0){
$intervale = 'il y a '.$diff->s.' sec';
}else{
$intervale = 'il y a '.$diff->i.' min';
}
}else{
$intervale = 'il y a '.$diff->h.' heure(s)';
}
}else{
$intervale = 'il y a '.$diff->d.' jour(s)';
}
$listNoti .= '<li>
<a onclick="link(event,\''.$resN['url_not_crm'].'\');updateEtatNoti(this,'.$resN['id_not_crm'].');" style="cursor:pointer;">
<span class="label label-icon label-success"><i class="'.$resN['icon_not_crm'].'"></i></span>
'.$notification->csNotification($resN['description_not_crm']).'
<span class="time">'.$intervale.'</span>
</a>
</li>';
}
echo $notification->getCountNewNotification().'***'.$listNoti;
}else{
echo 'NAN';
}
When I remove the notification code my application become more fast !
If your application is slowing down when you run the ajax every 3 seconds, try simplifying/shrinking the amount of work the page loaded by the ajax needs to do. Rather than reading an entire table, for example, try selecting only notifications with a "read" status of 0. That way, the .php file is faster to execute, meaning the ajax will not slow down the page as much.
Related
<?php
session_start();
define("HOST","localhost");
define("USER","root");
define("PASS","");
define("DB","project_inv");
define("DOMAIN","http://localhost/
inv_project/public_html/dont");
?>
Database:
<?php
class Database
{
private $con;
public function connect(){
include_once("constants.php");
$this->con = new Mysqli(HOST,USER,PASS,DB);
if ($this->con) {
return $this->con;
}
return "DATABASE_CONNECTION_FAIL";
}
}
//$db = new Database();
//$db->connect();
?>
JavaScript Validation Part: It comes here and keeps on loading when am trying to take from ip, e.g. http://xx.xx.xx.xx/inv_project/public_html/dont/
//For Login Part
$("#form_login").on("submit",function(){
var email = $("#log_email");
var pass = $("#log_password");
var status = false;
if (email.val() == "") {
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>Please Enter Email Address</span>");
status = false;
}else{
email.removeClass("border-danger");
$("#e_error").html("");
status = true;
}
if (pass.val() == "") {
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Password</span>");
status = false;
}else{
pass.removeClass("border-danger");
$("#p_error").html("");
status = true;
}
if (status) {
$(".overlay").show();
$.ajax({
url : DOMAIN+"/includes/process.php",
method : "POST",
data : $("#form_login").serialize(),
success : function(data){
if (data == "NOT_REGISTERD") {
$(".overlay").hide();
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>It seems like you are not registered</span>");
}else if(data == "PASSWORD_NOT_MATCHED"){
$(".overlay").hide();
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Correct Password</span>");
status = false;
}else{
$(".overlay").hide();
console.log(data);
window.location.href = DOMAIN+"/dashboard.php";
}
}
})
}
})
While am trying to run from other computer it displays the design and content of the page but it is not validating but when am trying locally it works fine.
Don't define DOMAIN as "localhost". This will cause errors, while calling the page from other computers.
Localhost means always the computer the script is running on. Using this in a JavaScript the reference to the server is lost and it tries to connect/forward to the client-computer - with no success. This works on the first computer, because this might be the server.
I have a big problem to make a progress bar in AJAX. The whole page is in AJAX, inside one of the webpage is AJAX which loads a function to get some big rows from the database.
I tried to make progress bar in this script in a foreach loop a flush() method and by writing/reading to $_SESSION, but still nothing. I really tried everything I don`t know how to do this. Need only this to complete my project. Could someone help me with this?
It is anyway which script I want to load, how is the template for this progress bar to use it in GET or POST ajax, for any AJAX.
<script>
jQuery(document).ready(function($) {
$(document).on('click','#save',function () {
setTimeout(getProgress,1000);
$(this).text('Pobieram analizę...');
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var id = $.urlParam('id');
var idt = $.urlParam('idt');
$.ajax({
url: "views/getresults.php?id="+id+"&idt="+idt,
success: function(data) {
$("#loadresults").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'views/listen.php',
success: function(data) {
if(data<=100 && data>=0){
console.log(data);
$('#loadresults').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / 100)*100 +'%">'+ data + '/' +100+'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#loadresults').text('Pobieram dane');
console.log('End');
}
}
});
}
});
</script>
and here is a getresults.php
foreach($result as $resul) {
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = 100;
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
and a get progress function listen.php
<?php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
?>
Writing and reading session doesn't work because the standard behavior of PHP is to lock the session file while your main code is being executed.
Try to create a file and update the its content with the percentage done during the execution of your function. Something like:
<?php
function slowFunction() {
$file = uniqid();
file_put_contents($file, 0);
// Long while that makes your stuff
// you have to know how many loops you will make to calculate the progress
$total = 100;
$done = 0;
while($done < $total) {
$done++;
// You may want not to write to the file every time to minimize changes of being writing the file
// at the same time your ajax page is fetching it, i'll let it to you...
$progress = $done / $total;
file_put_contents($file, $progress);
}
unlink($file); // Remove your progress file
}
?>
You can't get the progress of the data download from ajax. Once you request you to the server, the next response will be only after fetching the data or when the error occurs.
The solution to you is, get the data as fractions. Such as first download the 1/10th of the data, and in the success callback, recursively call the ajax again requesting the 2/10th data. On each success callback, you could change the progress bar.
Take a look at Server Side Events or Long polling as options
I've created a simple [voting form] using jQuery AJAX and JSON. I want to know how to create a Cookie so that the user will not be able to vote more than once. Following is my code.
I am new to Cookies and jQuery. Please tell me how to complete my task.
JavaScript
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("Is working " + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
});
});
</script>
PHP
<?php
$vote = $_REQUEST['vote'];
$filename = "poll_result.txt";
$content = file($filename);
// $decode = json_decode($encode);
$array = explode("||", $content[0]);
$male = $array[0];
$female = $array[1];
if ($vote == '0') {
$male = $male + 1;
}
if ($vote == '1') {
$female = $female + 1;
}
$insertvote = $male."||".$female;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$table = (
"<h2>Results:</h2>
<table>
<tr>
<td> Male :</td>
<td>
<img src='poll.gif'
width= ".(100*round($male/($female+$male),2)).
"height='20'>".
(100*round($male/($female+$male),2))." %" .
"
</td>
</tr>
<tr>
<td> Female :</td>
<td>
<img src='poll.gif'
width=". (100*round($female/($female+$male),2)) .
"
height='20'>".
(100*round($female/($female+$male),2))." %" ."
</td>
</tr>
</table>"
);
$list = array('vote' => $table);
$encode = json_encode($list);
echo $encode;
?>
HTML
<div id= "poll">
<h3> What is your Gender? </h3>
<form>
Male :
<input type ="radio" name ="vote" id="vote1" >
<br>
Female :
<input type ="radio" name ="vote" id="vote2" >
</form>
</div>
You would want to set a cookie when the user votes, and check for that cookie in PHP when a vote is submitted. If the cookie is already set, the vote should be discarded.
For example, using just PHP, it could look something like this:
if (!isset($_COOKIE['has_voted'])) {
// normal vote submission code goes here
// ...
// then we set a cookie to expire in 30 days
setcookie('has_voted', '1', mktime().time()+60*60*24*30);
} else {
// cookie already exists, user has already voted on this machine
// do not count the vote, flag an error to the user
}
It is worth noting that there are ways round this - the user could easily delete the cookie manually. In this case, you could also store the IP addresses of users who have already voted, but this can open up problems on shared machines and multiple machines behind a network.
Since it seems you're using PHP, you'll be able to implement a cookie to prevent multiple votes within your already existing script.
The syntax for setting a cookie in PHP is as follows:
setcookie("cookiename", "cookiedata", cookietime, "cookielocation");
Where "cookiename" is the name of the cookie, for example, "voted", "cookiedata" is the data stored in the cookie– "yes", for example. "cookielocation" is the location where the cookie is stored in the user's browser cache. Unless you know what you're doing, just set this to "/".
Cookietime is how long the cookie will sit in the users system until the browser automatically deletes it. Note that this doesn't prevent the user from deleting the cookie. For simplicity, I usually set the time as follows:
time()+60*60*24*days
Where days is how long the cookie will sit in the user's system (in days, of course).
To retrieve the value of a cookie so you're able to perform logic on it, try using:
if(isset($_COOKIE['cookiename'])) {
$valueOfCookie = $_COOKIE['cookiename'];
}
Make sure to use the if(isset()) to make sure the cookie has been set, before trying to retrieve the value.
Using these functions, your logic may look something like this when the user submits the form:
Check if the voting cookie is set
If it is, print an error message, else:
Continue to process the form data, and set the vote cookie
However, on a side note, if you're concerned about users potentially deleting their cookies so they can vote again, I might suggest that, rather than using cookies, you store users' IP addresses on the server-side, and deny them voting access if their IP address has already voted.
You could do this with sessionStorage, using only JS:
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
if ( sessionStorage.getItem( 'voted' ) == 'true' ) {
alert('You have already voted!');
}else if ( sessionStorage.getItem( 'voted' ) == null ){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("It's working" + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
sessionStorage.setItem('voted', 'true');
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
}
});
});
</script>
What I have done here is added a session storage item in the
complete callback of your ajax call, so once it has completed the
item 'voted' will be set.
I have then wrapped the ajax call in an if condition which checks
the value of the storage item and if it is set then will not allow
you to vote (and instead bring up an alert)
Note that you can also you localStorage if you want the item to last longer as sessionStorage is cleared when the browser window is closed while localStorge will last until the user clears their cookies / browsing data.
And here is a little snippet you can use to clear the storage for testing purposes:
$('#clear').click(function(){
console.log(sessionStorage.getItem( 'voted' ));
sessionStorage.removeItem('voted');
console.log(sessionStorage.getItem( 'voted' ));
});
You will need the accompanying HTML with that:
<p id="clear">clear</p>
I have a bit of javascript that posts to a php, every second, which checks a schedule and basically returns "refresh" if the start time is met then returns refresh when the end time is met.
if "refresh" it reloads the page showing what its suppose to.
function checkSchedules(){
if(sch_timer)
clearInterval(sch_timer)
$.ajax({
url:'checkSchedule_test.php?mediaID='+mediaIDArray[schCount],
type:'GET',
complete: function (response) {
if(response.responseText == "refresh"){
location.reload(true);
}
},
error: function () {
alert('Sorry there was an error!');
},
})
sch_timer = setTimeout(checkSchedules,1000);
schCount = (schCount >= urlArray.length - 1)? -1 : schCount
++schCount
}
in the php
if ($current_date>=$startDate && $current_date<=$endDate){
if ($current_time >= $startTime && $current_time <= $endTime){
$timeout = $endTime - $current_time;
if ($current_time >= $startTime && $current_time <= ($startTime+3000)){
echo "refresh";
}
if($timeout<=3000){
echo "refresh";
}
}
}
when the start time is met it refreshes fine, works great.
then when the end time is met it refreshes but the contents the same.
if I hit refresh it works fine.
I've tried different methods of reload() (document.reload, etc...)
Has anyone got any ideas?
Cheers
use console to understand what is returning from server
use debug() or console.log() for understand what is returning from php ... reload script is correct issue will be during ajax
Hi I am tring to implement the comet with PHP and jquery. The comet is started on every page load. However it cause loading of any page in the website become very slow like 10 seconds, it seem to be waiting for the previous request to the server to die() at the if($elapse > 10)
But if a ajax connection connection is aborted, isn't the PHP should stop executing furher ? Any idea why reloading page become slow ?
function getPendingCheckin()
{
ignore_user_abort(false);
$iCreatedDate = $this->input->post("iLastCreateDate");
$aCheckin = [];
$prev = time();
while(! $aCheckin )
{
$aCheckin = $this->getData();
if($aCheckin || connection_aborted() == 1)
{
break;
}
else
{
sleep(1);
$elapse = time() - $prev;
if($elapse > 10)
{
die();
}
}
}
header('Content-type: application/json');
echo json_encode($aCheckin);
}
Javascript
$(window).ready(function(){
var iLastCreateDate = $('#iLastCreateDate').val();
function startGetPendingCheckin()
{
$.ajax({
type: "POST",
url: "/kc/comet/getPendingCheckin",
data: 'iLastCreateDate=' + iLastCreateDate,
error : function(msg)
{
//alert("Error get pending checkin");
},
success :function(o)
{
if(o)
{
//process data
}
startGetPendingCheckin();
}
});
}
startGetPendingCheckin();
})
No, php execution is not (always) aborted. I noticed that on heavy scripts runned on local machine.
You may fail to run 2 parallel request to php scripts due to not closed session. Usually it is auto-closed after termination of the script. With default behavior (sessions in lockable files, no manual closing) it is not possitble to have 2 simultaneous requests from the same user — the latter would be blocked by the former and will wait for its termination.
You may close session as long as you checked everything about user authorization.