I am using jQmodal plugin , to show pop up window, welcome to site.
But the issue is every time page refresh window pop-up.
Here is my code http://jsbin.com/atoqe5/3/edit
I think it can be done using Cookies, but not much Idea how to use that. :(
Thanks!
You could set a cookie with JavaScript and set it to true when it's opened for the first time.
These are just helper functions for setting and getting cookie values, more info about setting and getting cookie values.
function setCookie(name, value, daysToLive) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + daysToLive);
document.cookie = name + '=' + escape(value) + ((daysToLive == null) ? '' : '; expires=' + expirationDate.toUTCString());
}
function getCookie(name) {
var cookies=document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
if (cookies[i].substr(0, cookies[i].indexOf('=')).replace(/^\s+|\s+$/g, '') == name) {
return unescape(cookies[i].substr(cookies[i].indexOf('=') + 1));
}
}
}
Prevent the modal from opening if the value is set:
$(function() {
if (!getCookie('modalOpened')) {
// Put your code to open the model here...
// Set value to true to prevent the modal from opening again
setCookie('modalOpened', true);
}
});
If you are using php you can do something like this: put in each page as first line
<?php session_start(); ?>
and in you homepage
<?php session_start();
if( $_SESSION['visited'] ){
//don't show the modal box
} else {
$_SESSION['visited'] = true;
//show modal box;
}
?>
This code check if you already visited the page in this session, if you don't shows the modal box, then set the global session variable $_SESSION['visited'] to true, so you can be sure the user have already visited the page :)
hope this helped
Related
I'm failing to save the info to when a logged in user clicks on the favorite button.
This is my first week in javascript class(including ajax). We're allowed to copy paste as long as we understand the process. So the first thing I did was looking up tutorials as to how to make favorite / unfavorite buttons and took over a template. Then I searched up how save the info in the database once the user clicks the favorite button. I'm not sure linking to external websites is allowed but I specifically took over this code:
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
faves = myfaves;
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
</script>
</head>
<body>
Add me to fav
<ul id="appendfavs">
</ul>
</body>
</html>
It displays "add me to fav" like it's supposed to but then when I click on it, it returns:
(index):54 Uncaught TypeError: Cannot read property 'push' of null
at HTMLAnchorElement.<anonymous> ((index):54)
at HTMLBodyElement.dispatch (jquery.min.js:3)
at HTMLBodyElement.r.handle (jquery.min.js:3)
The assignment is as follows:
""- Show a 'favorite' icon / heart. Make this clickable via jQuery / JavaScript. If you click on it, an AJAX request must be sent with the blog post id. A WP plugin must 'process' the AJAX request, and store in the session (or database) that user X has liked a certain blog post. The server must return a JSON response."
Now had a small side question, for after I resolve the error of this thread, is my way of thinking correct:
Through CSS I'll create a heart button
This script itself does the ajax request with post ID
WP plugin I've done before
This script provides the JSON response
Thank you stack overflow in advance, I look forward to learning!
I have a string array in javascript. But when I use href='mypage.php?id=var', I lost this array. I need keep it out for use it in the $_GET. This is the code:
<script>
var element_selected=[];
var i = 0;
function hrefPage()
{
var pagina = "index.php?id=renew";
location.href = pagina;
}
function loadArray(value)
{
element_selected[i] = value;
i++;
}
</script>
<?php
if(isset($_GET['id']))
{
if ($_GET['id'] == "renew")
{
$selected_elements = array();
$j = 0;
for($j = 0; $j < "<script> document.write(i) </script>"; $j++)
{
$selected_elements[j] = "<script> document.write(elements_selected[j]) </script>";
echo $selected_elements[j];
}
}
}
?>
You need to use local storage to use retain javascript variables value across page reloads
var varName = "sachin";
localStorage.setItem("varName", VarName);
alert(localStorage.getItem("varName"));
Another example how to store array in localstorage
var arrayName= [];
arrayName[0] = prompt("Enter your value");
localStorage.setItem("arrayName", JSON.stringify(arrayName));
//...
var storedValues = JSON.parse(localStorage.getItem("arrayName"));
I have added a simple example here how to set javascript value in localstorage and how to access it
I have provided it as an information for you to retain value across page reloads
but first thing about http is that it is a stateless protocol .Each request fetches data from server and renders it in browser the value here is set in local storage of browser .So if you want to reload some value to script after page reload you need to set some flags and on page load check that flag if flag condition for the required situation arises get data from localstorage else proceed as normal
Check out this tutorial for more information
I have used the Asp.Net Identity framework in my app.There is a need, when the session expires give a prompt message, and then jump to the login page instead of directly jump to the login page.Prompt information using custom styles.
Because my app's left menus load the view with ajax,so I overried the AuthorizeAttribute.HandleUnauthorizedRequest methord to return a json.Now when users click left menus, it can work properly.But if users refresh the page by click F5,the page will still jump directly to the login page.
I have already overrided AuthorizeAttribute.HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var httpContext = filterContext.HttpContext;
string sintab = httpContext.Request["inTab"];
if (!string.IsNullOrEmpty(sintab) && bool.Parse(sintab))
{
var result = new JsonResult();
result.Data = new
{
Authorize = false,
Url = LOGIN_URL
};
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result =result;
return;
}
if (filterContext.Controller.GetType() != typeof(Controllers.HomeController) &&
!filterContext.ActionDescriptor.ActionName.Equals("Index", StringComparison.OrdinalIgnoreCase))
{
string returnUrl = "/" + filterContext.Controller.GetType().Name.Replace("Controller","") + "/Index" ;
returnUrl = httpContext.Server.UrlEncode(returnUrl);
httpContext.Response.Redirect("~/Account/Login?ReturnUrl="+returnUrl);
return;
}
base.HandleUnauthorizedRequest(filterContext);
}
The code of left menus' loadView js
$.get(url, null, function (html) {
html = html.replace(/#%/g, "\"").replace(/%#/g, "\"");
var json;
try {
json = eval("(" + html + ")");
} catch (e) {
}
if (json && !json.Authorize) {
// give an message
layer.alert("Session timeout, please re login.", function (index) {
window.location.href = json.Url + "?returnurl=" + encodeURI(hash);
});
}
else {
$("#content").empty().html(html);
_initModalButton();
$("#content").show();
}
}, 'html');
The page looks like this image
I want to know if there are some better ways to do this because there are a lot of other button need to check authorize status and show message before jump to the login page,and how to give the message when users refresh the page?
Thanks very much!
I think you're looking for are Global Ajax Events.
Please, check this, I think this make your job easier.
I am new to PHP and I want to know if something like this is possible. Basically on my web server I have multiple index files. Ex. Christmas.html, normal.html, Halloween.html. Is there a way to make an index.php file that will redirect you to a certain page on a certain date? So if it’s about Christmas time, the PHP page will redirect you to the Christmas.html page. Thank you!
I've tried this
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+ (((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
if((new Date().today()) >= "01/08/2014")
{
location.href ="new location url";
}
else
{
location.href="current location url";
}
but I don't want to have to change the date every year for it to work again. Is there a way to fix this?
Of course, you can use the header function in PHP to set a new location for example.
$month = (int)date('n');
$day = (int)date('j');
if ($month == 12 && $day >= 24 && $day <= 26) {
header('Location: Christmas.html');
}
Instead redirecting, you can use include function.
It will keep your page url same but content will be included within it.
include 'Halloween.html';
I am making a website that uses the Javascript Parse SDK and calling Parse.User.current() only works some of the times causing my redirect to kick users back to the login page even though Parse.User.logOut() has not been called. I am using the User class and not having them login through Facebook.
Function to see if there is an active session. If there is, the page loads, otherwise the user should be redirected to the main page:
function checkUser(){
var currentUser = Parse.User.current();
if (currentUser) {
//the page loads
} else {
//redirect user to the login page
window.location = 'login-url';
}
}
The above code is called in the <head> tag of each page:
<script>checkUser()</script>
When the user logs in, I check to make sure Parse.User.current() is not null and then redirect them to the main page. The first time they are sent to the main page, the checkUser() function does not find a user, and they are sent back to the login page where my redirect() function (below) sends them back to the main page because Parse.User.current() is not null when it checks it. The second time they are sent to the main page, Parse.User.current() has a user, so they stay on this page.
To a user logging in, the above is not a problem, since after logging in, they end up on the right page, but the real issue arises when the user tries to navigate to a different page using the tabs name. When one of these is clicked, checkUser() on the new page does not find a user so the user is pushed back to the login page, where redirect() does find a user and sends them back to the main page where checkUser() finds a user as well, so they end up back on the main page again.
I do not know what the issue is, but I think it has something to do with initially changing the pages programatically because if I log in and then type the url of a different page into my address bar instead of clicking on a tab, the checkUser() finds a user and then I can use the tabs to switch pages without a problem. Additionally, it all occasionally works perfectly when I am using Chrome (this problem always occurs with Firefox) and then I log out and log back in and the same issue comes back.
My login code:
$("#login").submit(function(event){
event.preventDefault();
var name=$("#username").val();
var password=$("#password").val();
Parse.User.logIn(name, password, {
success: function(user){
if(Parse.User.current()){
window.location="main-page";
} else{
alert("no user");
}
}, error: function(user, error){
alert("login error:" + error.message);
}
});
});
Redirect called on the login page:
function redirect(){
var currentUser = Parse.User.current();
if (currentUser) {
//a user is found, so they are taken to the main page
window.location = 'main-page';
} else {
//the user has to log in
}
}
I was able to solve my problem by storing the userid in a cookie instead of relying on Parse.User.current(). I essentially just followed the steps outlined in http://www.w3schools.com/js/js_cookies.asp and since the login function I was using has a callback with the object, I could easily get the user's id when they log in using user.id.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
//stay on page
} else {
window.location.href="login-url";
}
}
function removeCookie() {
setCookie("userid", "", -1); //setting the userid to an empty string
//and setting the expiration time to have passed
}
On the login and signup callback, I set the cookie and then redirect to the main page
setCookie('userid', user.id, 1);
window.location.href="main-page-url";
On all pages that require a user to be logged in, I check the cookie by calling checkCookie(); in the <head>. On the signin page, I also have a redirect so that if the user is signed in, they are redirected to the main page. This function is the same as checkCookie(), but I redirect when there is a user instead of when there is not one.
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
window.location.href="main-page-url";
}
}
When the user logs out, I still call Parse.User.logOut(); but I also call removeCookie(); before redirecting to the log in screen.