Display notification only once - PHP - Codeigniter - JS - php

There is an ajax function, which displays a notification on the home page, however, every time I enter thehome page, or refresh the F5 page, the notification is displayed again.
How to fix this?
Is there any way to do this, using js jquery or PHP?
Below the code I have:
Controller
public function get_message()
{
$notification= array();
$notification['message'] = 'message test';
$notification['type'] = 1;
echo json_encode($notification);
}
Javascript
/*** variable ***/
var enum_toastr_type = {
success: 1,
info: 2,
warning: 3,
error: 4
}
/*** PageLoad start ***/
$(document).ready(function() {
toastr.options = {
closeButton: true,
positionClass: 'toast-bottom-right',
timeOut: '20000'
}
get_message_ajax();
});
/*** PageLoad end ***/
function show_message_toastr(mensagens) {
$(mensagens).each(function() {
switch (this.tipo) {
case enum_toastr_type.info:
toastr.info(this.message);
break;
case enum_toastr_type.success:
toastr.success(this.message);
break;
case enum_toastr_type.warning:
toastr.warning(this.message);
break;
case enum_toastr_type.error:
toastr.error(this.message);
break;
}
});
}
/*** Ajax start ***/
function get_message_ajax() {
$.ajax({
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
url: "helper/get_message",
success: (function(data) {
//console.log(data);
_obj = JSON.parse(data);
show_message_toastr(_obj);
}),
error: (function(erro) {
handle_ajax_error(erro);
})
});
}
/*** Ajax end ***/

For doing this you will need to set cookies in the browser to track if user has visited this page already. This would also prevent this on page reloads. You can use local storage to store any data in the browser.
// on page load check if user has not already visited this page
var visited = localStorage.getItem('visited');
if(!visited) {
// call your ajax function which displays message
get_message_ajax();
// lets set visited to true so when user loads page next time then get_message_ajax() does not gets called
localStorage.setItem('visited', true);
}
If you need something like; what if user logs out of the system, then you can clear the local storage on logout. Maybe you can add click listner on logout button and can clear local storage.
localStorage.clear(); // this will clear all website data in localStorage
// or you can update visited key;
localStorage.setItem('visited', false);
Or if you want something more advance like even user does not logs out and still you want to show message lets say if user visits after 1 day. Then you can store timestamp with key and parse it back when checking if user visited.
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
When accessing the key you can do something like this;
var object = JSON.parse(localStorage.getItem("key")),
dateString = object.timestamp,
now = new Date().getTime().toString();
// here you can compare two time strings and decide to show message.
For different implementation and ideas on how to manipulate time here is some help;
https://developer.mozilla.org/en-US/docs/Web/API/Storage
When do items in HTML5 local storage expire?

Related

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

Jquery keyup Event with AJAX causing incorrect results

I have the following Jquery code that listens to a user typing in a captcha and sends an ajax request on each keyup to see if the correct code has been typed:
$('#joinCaptchaTextBox').keyup(function() {
$.get('scripts/ajax/script.php', {
'join_captcha': '1',
'captcha': $('#joinCaptchaTextBox').val()},
function(data) {
var obj = JSON.parse(data);
if(obj.ajaxResponse.status) {
$('#joinCaptchaNotAcceptable').hide();
$('#joinCaptchaAcceptable').show();
}else{
$('#joinCaptchaAcceptable').hide();
$('#joinCaptchaNotAcceptable').show();
}
});
});
The PHP script on the other end just checks the session and replies:
if($siteCaptcha == $_SESSION['secretword']) {
$this->captchaCompare = TRUE;
}else{
$this->captchaCompare = FALSE;
}
This works fine 95% of the time but I'm finding sometimes it reports the captcha typed is incorrect even though its correct. I think this could be because when typed fast many requests are sent to the server and the order or requests coming back isn't the order sent and therefore (as only one will be correct) a prior one is recieved last and incorrect is displayed.
Is there a better way to do this? Is there a way to ensure the last request sent is recieved last? Is there something I'm missing here. I can give more info.
thankyou
Add a timeout so as to not send a request on every keyup when the user types fast:
$('#joinCaptchaTextBox').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
var data = {
join_captcha: '1',
captcha : $('#joinCaptchaTextBox').val()
};
$.ajax({
url : 'scripts/ajax/script.php',
data: data,
dataType: 'json'
}).done(function(result) {
$('#joinCaptchaNotAcceptable').toggle(!result.ajaxResponse.status);
$('#joinCaptchaAcceptable').toggle(result.ajaxResponse.status);
});
},500)
);
});

common server response page causes in ajax?

I have developed an facebook app which is using ajax request/response each 3secs. and also there are menu items which are loading content in main div. Every ajax request is going to common.php. Few ajax are very slow. I want to know that using a single file for all request is slowing performance?
Here is ajax request which is slow:
function FetchMore()
{
document.getElementById("debugger").innerHTML = "Fetch more called";
attempt++;
/*********proccessing ajax***********/
document.getElementById("bldr").style.display="";
var urlp="https://www.shopinion.net/facebook/common.php?FBUID="+fbuid+"&action=more&attempt="+attempt+"&what="+lstevt;
if(lstevt == "home" || lstevt == "rec")
{
if(complete==false)
{
complete=true;
setTimeout("Watcher()",10000);
document.getElementById("debugger").innerHTML = "Reqest send Fetch more called";
MoreAjaxReq = $.ajax({
async: true,
url: urlp,
cache: true,
success: function(data) {
complete=false;
document.getElementById("debugger").innerHTML = "Data received Fetch more";
setTimeout("getScroll()",3000);
document.getElementById("content").innerHTML +=data;
document.getElementById("content").style.opacity="1";
Tip();
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
var handler = null;
// Prepare layout options.
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#content'), // Optional, used for some extra CSS styling
offset: 6, // Optional, the distance between grid items
itemWidth: 210 // Optional, the width of a grid item
};
$(document).bind('scroll', onScroll);
// Call the layout function.
handler = $('#tiles li');
handler.wookmark(options);
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
document.getElementById("bldr").style.display="none";
//FB.Canvas.scrollTo(0,400);
setTimeout("Trick87()",3000);
}
});
}
//
Please help me how to improve response time?
Thanks in advanced.
Oh, there are lots of ways to improve performence. I will list a few
Cache data on server side
Minimize the content in the response
Maybe you don't have to fetch more data if the first request hasn't success yet.
Use as few database calls as possible

change login page from jquery to php-mysql

I have made some page for show all data from DB. And also, I can edit the data from this page.
Berofe do some editing, some JQuery Dialog will appear and then ask our user or password.
I have made some simple login use Jquery, like:
$("#enter").click(function(){
if($('#user').val() == "admin" || $('#pass').val() == "qaubuntu") {
$("#dialog").dialog('close');
$("#segment").show();
}
if($('#user').val() == "user" || $('#pass').val() == "user") {
$("#dialog").dialog('close');
$("#content").show();
}
});
But, this only for one user. I need to add 5 user again for different page access. how should I do to change this login into php and mysql?
I'm not really understand how to login for different access page for each user.
thanks for advance.
ex:
user = admin ---> just can access #segment
user = user and foo --> can access #content
You culd use jQuery, Php, and mysql.
NOTE: Not tested but it will get you started
Well first off i wuld start by building a usertable in your DB, Lets say you have the following fields:
"Username" "password" "privilage" <-( set to INT where 1="admin" 2="user")
Then you shuld create the login form (lets say tou have the inputs id="username" and id="password") and a button "login" with id="login".
Now some jQuery:
$(document).ready(function(){
$('#login').click(function(){ // Grab button "login" on click event
var usr = $("#username").val(); // Grab field value from input "username"
var pas = $("#password").val(); // Grab field value from input "password"
var dataString = "usr="+usr+"&pas="+pas;
//Now send your data to a backend file (Php) using $.ajax
$.ajax({
type:'POST',
data: dataString,
url:'backendfile.php', /// loaction and backend filename
success: function(data){ // Callback
// DO STUFF LATER SEE jquery Callback below
}
});
});
});
And for backend.php
//Create your DB connection first
// grab POST
$usr = $_POST['usr'];
$pas = $_POST['pas'];
//Sql call
$sql = "SELECT privilage FROM tabel_name WHERE username='".$usr."' AND password='".$pas."'";
if(myslq_query($sql)){
$priv = mysql_fetch_assoc($sql);
/* will return 1 or 2 depending on the privilage set in you DB where 1 is admin and 2 is user */
echo $priv['privilage'];
}else{
echo 0; // If login fails
}
Now go back to jQuery: (handle Callback)
In the success section of your previous ajax call.
success: function(data){ // Callback
switch(data){
case 1:
// Do stuff if privilage is 1 (admin)
$("#dialog").dialog('close');
$("#segment").show();
break;
case 2:
// do stuff if result is 2 (user)
$("#dialog").dialog('close');
$("#content").show();
break;
default:
alert('wrong username or password');
break;
}
}
There you go!
Its not tested, so you may confront some problems but, hey it il get you started.
Tip! encrypt the password

How to alert or warn a user that session will be expiring soon in php codeigniter

Basically I'm looking for a solution where a user is notified five minutes before the session expires.
The ideal solution will be count down notification that will have an option to renew the session.
If the countdown timer expires without the user refreshing the page, I need to log them out.
Since the session will be refreshed as soon as you go back server-side and the script calls session_start() you really need to do this in Javascript. However if the user has two browser windows open with a split session and one is inactive, while the user is still generating traffic with the other, then the javascript in the idle window would incorrectly report that the session was about to expire. So you'd need to implement your own ajax wrapper to detect the age of the session without calling session_start().
Something like:
$session_id=$_REQUEST[session_name()];
// if you use the default handler:
$session_last_access=filemtime(session_save_path() . '/' . $session_id);
$time_left=time() + session_cache_expire() - $session_last_access;
C.
Depends on what exactly you want to achieve. When someone uses multiple tabs/windows, a window can stay open for very long without the session expiring. AJAX operations complicate things even further. If you want accurate notifications, you will have to set up a timer, and when it fires, check via an AJAX request (taking care not to renew the session) whether the estimate is still accurate.
Added this script in view:
`
if(isSessionAlive >0)
{
var timer = {
time: 0,
now: function(){ return (new Date()).getTime(); },
start: function(){ this.time = this.now(); },
since: function(){ return this.now()-this.time; }
}
var timerId;
sess_expiration = <?=($this->config->config["sess_expiration"]*1000)?>;
alertTime = <?=($this->config->config["sess_time_to_alert"])?>;
timerId = window.setTimeout("pingCI()",sess_expiration-((alertTime*1000)));
jsBaseurl = "<?=($this->config->config["base_url"])?>";
}
function resetTimer(resetTime)
{
//alert('RESET Time'+resetTime);
window.clearTimeout(timerId);
timerId = window.setTimeout("pingCI()", resetTime);
return;
}
function pingCI()
{
if(isSessionAlive > 0)
{
$.ajax({
type: "POST",
url: "<?= site_url('users/getSessionTimeLeft') ?>/",
data: "sessid=<?=$this->session->userdata("session_id")?>",
success: function(transport)
{
response = transport;
if(response=='')
{
parent.location.assign(jsBaseurl+'users/logout');
}
else if((response<=(alertTime*1000)) || (response-1000<=(alertTime*1000)))
{
alertSessionTimeOut(response);
}
else
{
resetTime = eval((response - alertTime)*1000);
resetTimer(resetTime);
}
}
});
}
}
function alertSessionTimeOut(alertTimeExp)
{
if(isSessionAlive>0)
{
var response='';
var timerIdEnd;
timerAlert = window.setTimeout("forceLogout()",alertTimeExp*1000);
timer.start(); // start counting my friend...
fConfirm = confirm('Your Session is about to time out. Please click OK to continue the session');
if(timer.since() >= (alertTime*1000))
{
parent.location.assign(jsBaseurl+'users/logout');
}
if(fConfirm ==true)
{
$.ajax({
type: "POST",
url: "<?= site_url('users/keepAlive') ?>/",
data: "sessid=<?=$this->session->userdata("session_id")?>",
success: function(transport)
{
response = transport;
if(response=='')
{
parent.location.assign(jsBaseurl+'users/logout');
}
window.clearTimeout(timerAlert);
resetTimer(sess_expiration-((alertTime)*1000));
}
});
}
else
{
//parent.location.assign(jsBaseurl+'users/logout');
window.clearTimeout(timerAlert);
window.clearTimeout(timerId);
}
}
}
function forceLogout()
{
parent.location.assign(jsBaseurl+'users/logout');
}
And in Users Controller:
function getSessionTimeLeft()
{
$ci = & get_instance();
$SessTimeLeft = 0;
$SessExpTime = $ci->config->config["sess_expiration"];
$CurrTime = time();
$lastActivity = $this->session->userdata['last_activity'];
$SessTimeLeft = ($SessExpTime - ($CurrTime - $lastActivity))*1000;
print $SessTimeLeft;
}
function keepAlive()
{
$this->load->library('session');
$this->session->set_userdata(array('last_activity'=>time()));
if(isset($this->session->userdata["user_id"])) print 'ALIVE';
else print '';
}
`
One way is to store in one javascript variable the time remaining, and update the variable in every page refresh
Create one javascript function with one settimeout that verifies the value of the variable that you set in 1.)
Regards,
Pedro

Categories