I am trying to set up cookies that expire in 7 days after clicking the 'x' on the modal. I can't figure out why it doesn't want to save the cookie. Below is the code I am using. The site is goodbooks.io.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"> </script>
<script>
var cookieName = 'popupClosed';
if(typeof Cookies.get(cookieName) !== 'undefined') {
$('.popup-wrapper, .preview-page, .popup-content-wrapper, .popup').remove();
}
$('.close-popup').on('click'), function(){
Cookies.set(cookieName, 'value', { expires: 7});
}
</script>
in PHP
<?php
header('Test 123 I Love Bacon'); // just to test header_ list
setcookie('cookieName','cookieValue123',time()+604800, "example.com");
if(isset($_COOKIE['cookieName']) && $_COOKIE['cookieName'] == 'cookieValue123')
{
var_dump(headers_list()); // show headers to be sent to the browser
}
?>
Change
$('.close-popup').on('click'), function(){ ... }
to
$('.close-popup').on('click', function(){ ... })
Related
I'm attempting to create a redirect based on a cookie existence. So when a user connects to my website jonathanstevens.org for the first time, they are redirected to jonathanstevens.org/landing
Code parts:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
Global.js
function create_cookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime( date.getTime() + (days*24*60*60*1000) );
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function get_cookie(name) {
var nameEQ = name + "=";
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, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Index.html
<!-- redirect to landing page -->
<script>
// Redirect to landing page if 'form_submitted' cookie does not exist
if (get_cookie('secondvisit') === 'undefined') {
window.location.href = "landing.html";
}
</script>
landing.html
<!-- Adds second Visit cookie -->
<script>
jQuery(document).ready(function($) {
// Create cookie so that the user is no longer redirected
create_cookie('secondvisit', 'true', 30);
});
</script>
The expected result was it to check for a cookie, then forward me to my landing page if it wasn't defined. Any ideas on what I've done wrong?
You should compare with null instead of undefined as you are returning null from the function get_cookie
Index.html
<!-- redirect to landing page -->
<script>
// Redirect to landing page if 'form_submitted' cookie does not exist
if (get_cookie('secondvisit') === null) {
window.location.href = "landing.html";
}
</script>
Apart from this you should use this library really good one an easy to work with see below
Create a cookie, valid across the entire site:
Cookies.set('name', 'value');
Create a cookie that expires 7 days from now, valid across the entire site:
Cookies.set('name', 'value', { expires: 7 });
Create an expiring cookie, valid to the path of the current page:
Cookies.set('name', 'value', { expires: 7, path: '' });
Read cookie:
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
Read all visible cookies:
Cookies.get(); // => { name: 'value' }
Delete cookie:
Cookies.remove('name');
Delete a cookie valid to the path of the current page:
Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!
EDIT
A converted version of your code using js.cookie library will look like following.
(Note: i have tested this code and it works correctly, make sure you are including the library correctly and there are no errors on the console.)
Index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<!-- redirect to landing page -->
<script>
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = "landing.html";
}
})
// Redirect to landing page if 'form_submitted' cookie does not exist
</script>
landing.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<!-- Adds second Visit cookie -->
<script>
jQuery(document).ready(function () {
// Create cookie so that the user is no longer redirected
var a = Cookies.set('secondvisit', 'true', {
expires: 7
});
});
</script>
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.
I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.
UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.
Image Index Page:
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'] {
$_SESSION['Worksafe_Mode'] = 1;
}
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
Toggle Worksafe Mode
</button>
<script>
$('#Worksafe_Button').click(function() {
$.post("worksafe_mode_toggle.php")
.done(function(data) {
window.location.href = window.location.href;
});
});
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');
while($row = mysqli_fetch_assoc($image)) {
if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
echo 'If you are over 18, toggle Worksafe Mode to view this image';
}
else {
echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
}
}
?>
worksafe_mode_script:
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 1) {
$_SESSION['Worksafe_Mode'] = 0;
}
else {
$_SESSION['Worksafe_Mode'] = 1;
}
}
I think ajax is a good approach in your case.
I might do something like display a page of SFW images as the default, along with the toggle button.
When they click the button it triggers an ajax request to the back-end that sets/un-sets the session value in toggleWorksafe.php. Finally it triggers a page refresh.
During the page refresh the PHP code checks whether the session variable is set and shows either the filtered or unfiltered set of images, and changes the button's text to match.
To implement:
Include jQuery in the <head> section (jQuery simplifies the ajax call):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'])) {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
<button id="workSafe" type="button" name="Worksafe_Toggle_Button">
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo 'Hide NSFW images';
}
else {
echo 'Include NSFW images';
}
?>
</button>
<!-- display safe images by default -->
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo '<br/><br/>Showing NSFW images';
}
else {
echo '<br/><br/>Showing safe images only';
}
?>
<!-- any other page content here -->
<script>
$('#workSafe').click(function() {
// ajax request to page toggling session value
$.post("/toggleWorksafe.php")
.done(function(data) {
window.location.href = window.location.href; // trigger a page refresh
});
});
</script>
</body>
</html>
toggleWorksafe.php:
<?php
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 'yes') {
$_SESSION['Worksafe_Mode'] = 'no';
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
there are a couple of ways to do this and it related to how you hide or load you images.
1. simple method
if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:
var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false
function loadImage(nsfw){
if (nsfw){
$.get('nsfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
} else {
$.get('sfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
}
}
and in you button click event:
nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
2. another simple method, but not as simple as the #1
you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.
note: this method still uses cookie
for example the returned list is like this:
[
{"url": "some-image-1.jpg", "nsfw": "true"},
{"url": "some-image-2.jpg", "nsfw": "false"},
{"url": "some-image-3.jpg", "nsfw": "true"},
{"url": "some-image-4.jpg", "nsfw": "false"},
{"url": "some-image-5.jpg", "nsfw": "false"},
{"url": "some-image-6.jpg", "nsfw": "true"}
]
then you just render it when the conditions are met.
function renderImage(nsfw){
$.get('image-list-url', function(resp){
list.forEach(function(val, key){
if (nsfw || !val.nsfw){
$('#container').append('<img src="' + val.url + '/>');
}
});
});
}
and many other methods that are too long to explain, such as using Angular, React, or Vue
still uses cookie for between reloads or backs, and does not regard user's age.
as for the session based approach, you only need that if you need to verify your users age
that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use #KScandrett 's answer
Confirm form resubmission happens because you do not perform a redirect after a successful form submission.
Take a look at this wiki page to see how to do it right. https://en.wikipedia.org/wiki/Post/Redirect/Get
I'm working on joomla environment. I would like to run small php script by click on button event from JQuery reason I would like to use JQuery is I cannot modified existing component. Current component adding some values on Database from webpage. I would like to do same thing but from back-end with out notify any thing from another PHP file. I was trying something as code but it's not working.
Is there any other way.?
What is wrong in code.?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
$.post("/automate/UpdateMySql.php");
});
}
</script>
You were missing a dot and bracket(with semi-colon) at the end. As per the comments if you want to just Update Date And Time. You can post any random variable to UpdateMySql.php and then Create Date And Time there.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
In UpdateMySql.php write.
$clicked = $_POST['click'];
if(isset($clicked) && !empty($clicked)) {
$today = date("Y-m-d H:i:s");
$query = "UPDATE table_name date_time=".$today." WHERE anything = 'anything'";
if($query) {
return 'Updated';
} else {
return 'Something Went Wrong';
}
}
Please use:
$(document).ready(function() {
$('#submitButton').click(function(e) {
$.ajax({ type:'POST',
url:'/automate/UpdateMySql.php'
data:{name:'demo',id:"1"},
sucess:function(xhr) {
alert('table updated');
}
});
});
});
if some one need complete answer in future.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.
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