I am creating a popup plugin in WordPress. In my plugin, a popup opens on every page but I just want to show it on home page.
I know how to get it in PHP but don't know hot to get the home url in jQuery.
setTimeout(function(){
if($.cookie('SFPopup') == null){
$('#sfp_Modal').modal('show');
}else{
$('#sfp_Modal').modal('hide');
}
}, 3000);
This is how I am showing my popup using a cookie condition but I also want to show it only on home page not inner page.
This is my working code
<?php
function sf_display_popup(){
if (is_front_page() == true) {
?>
<script>
jQuery(document).ready(function($) {
$.cookieBar();
setTimeout(function(){
//var site_url = '<?php echo home_url(); ?>';
if($.cookie('SFPopup') == null || $('body').hasClass('home')){
// alert(site_url);
$('#sfp_Modal').modal('show');
}else{
$('#sfp_Modal').modal('hide');
}
}, 3000);
});
</script>
<?php
}
}
?>
try with checking body for class home. If body have home class it is home page.
if ($('body').hasClass('home')) { // show pop up }
I might be completly off, but wouldn't it be enough to check if document.location.pathname == "/" ?
That way you can check whether the adress is www.domain.com (<- would be root) or www.domain.com/something.
So if document.location.pathname == "/" you can execute your script and add the popup.
Related
So basically i got this code from online which allows you to load body content via ajax/php.
Site i got the code from:
https://www.webdesignerdepot.com/2014/02/how-to-supercharge-your-sites-speed-with-ajax-and-jquery/
If you look at that site(specifically the ajax/php demo, not the first jquery demo) you'll see that ajax loads load.php, then it loads different html files. Ive edited it to load different php files, however the loaded content displays the html code in my php file but not the php code(session name variable).
Here's the custom.js(ajax) file:
$(function() {
$('.left-sidebar a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
var $pageRoot = $linkClicked.replace('#', '');
if (!$(this).hasClass("current")) {
$(".left-sidebar a").removeClass("current");
$(this).addClass("current");
$.ajax({
type: "POST",
url: "load.php",
data: 'page='+$pageRoot,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#main-content').html(msg);
$('#main-content section').hide().fadeIn();
}
}
});
}
else {
event.preventDefault();
}
});
var hash = window.location.hash;
hash = hash.replace(/^#/, '');
switch (hash) {
case 'steal' :
$("#" + hash + "-link").trigger("click");
break;
case 'extort' :
$("#" + hash + "-link").trigger("click");
break;
case 'kill' :
$("#" + hash + "-link").trigger("click");
break;
case 'welcome' :
$("#" + hash + "-link").trigger("click");
break;
case 'profile' :
$("#" + hash + "-link").trigger("click");
break;
}
});
here's the load.php file:
<?php
if(!$_POST['page'])
die("0");
$page = $_POST['page'];
// echo $page; // rob, steal, extort, kill, welcome, profile
if(file_exists('pages/'.$page.'.php'))
echo file_get_contents('pages/'.$page.'.php');
else
echo 'There is no such page!';
?>
Here's the welcome.php file:
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
<section id="welcome">
<h2>Welcome Content</h2>
<p class="block">Welcome back, <?=$_SESSION['name']?></p>
</section>
And this is all i see when welcome.php is loaded:
Welcome Content
Welcome back,
After looking at years old post on here a lot of people mentioned needing to have session_start(); at top of file, i tried this and it said "ignoring session start cause a session has already been started".
So i found this on another post where someone else having a similar issue(unfortunately there was no answer for me there[nor for that poster])
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
I put the above code at the very top of welcome.php and when i load welcome.php without ajax i see this:
Array ( [loggedin] => 1 [name] => -Phil (Just-Us) [id] => 1 [role] => Admin )
Welcome Content
Welcome back, -Phil (Just-Us)
But when i load welcome.php via ajax i only see this:
Welcome Content
Welcome back,
UPDATE: So i added the below code to my home.php file of which houses the body content div and said div houses all the dynamically loaded content. And doing this works fine, i see my session name being displayed just fine. So does replacing load.php with welcome.php in the ajax code. So something is going wrong when ajax loads the load.php file and then load.php echo's another php files contents(leaving behind needed php content).
<script>
$(document).ready(
function() {
setInterval(
function() {
$("#main-content").load('pages/welcome.php');
}
, 10000 // 1000ms = 1 second. Lowest i'd go to is 0.05s which is 50ms. (even though the lowest it can go is 4ms apparently. not advised tho)
);
$.ajaxSetup({ cache: false });
}
);
</script>
Why is it that when i use the below code it opens the php file in a new tab rather than loading it into the specified div?
// Create event listener for all link clicks
document.querySelectorAll('page-links').forEach(link => {
link.addEventListener('click', (e) => {
// Retrieve href and store in targetUrl variable
let targetUrl = e.target.href;
// Output value of targetUrl to console
// console.log('A link with target URL ' + targetUrl + 'was clicked');
$("#main-content").load(targetUr);
});
});
I don't understand what is happening here. I have three pages.
Home.php
Nearmiss.php
Reports.php
Each of these pages has the following code at the top, with their own "thispage" variable defined specific to that page.
<?php
// home.php
if ( session_status() == PHP_SESSION_NONE ) {
session_start();
}
$_SESSION['thispage'] = 'Home';
echo('<div id="thispage" hidden>' . $_SESSION['thispage'] . '</div>')
?>
When I open each page and inspect the source I see exactly what I should see in that the hidden div contains the correct name of the page. However my app has an a function inside it that I'm trying to use to monitor $_SESSION in javascript for testing purposes. I'm doing an ajax call to logsession.php (below).
<?php
// logsession.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ( session_status() == PHP_SESSION_NONE ) {
session_start();
}
echo( json_encode( $_SESSION ) );
}
?>
My javascript function is written like this, and it just does a post to logsession.php and logs the results to the console.
let app = (function() {
var session = function() {
$.ajax({
type: "post",
url: "includes/logsession.php",
dataType: "json"
}).then( function( data ) {
console.log( data );
});
}
return {
session : session
}
}());
Can be called at the console using app.session();
I would expect to see the two of these synchronized as I click between pages, but when I log the session to console as I click between my navigation they do not match, with the ajax call often lagging one click behind the page I'm actually on. So for example, I'll go from "Home.php" to "Reports.php" and I will get a null value (as if $_SESSION hasn't been set yet) or I'll get { thispage: "Home" } when clearly I just navigated to Reports.php.
My navigation is done with bootstrap.
<!-- Navbar Left -->
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="lnkHome">Home</li>
<li id="lnkNearmiss">Nearmiss</li>
<li id="lnkReports">Reports</li>
</ul>
</div>
My navbar is setup so that styles are applied automatically when clicked using some javascript in a refresh function, which just adds and removes an "active" class to it with some styles. Inside this I'm calling my session.
let refresh = (function() {
var navbar = function( element ) {
$('#navbar ul li').removeClass('active');
$(element).addClass('active');
app.session();
}
return {
navbar : navbar
}
}());
The click events that are wiring up my links to the refresh.navbar(); function look like this.
$(document).on('click', '#lnkHome', function() {
if ( $('#thispage').html() != 'Home' ) {
// note, references the content of the hidden divs
refresh.navbar( this );
}
});
As I'm clicking through my links this is what I see. Starting on the Home.php, I clicked sequentially through every few seconds to Nearmiss.php and then Reports.php and you can see that sometimes its fine and then its not, which you can see on the last two clicks.
Count 20 was actually on Nearmiss.php
Count 21 was actually on Reports.php
Timestamps included.
Why would Ajax ever return old information?
Environment
- Local web server on my LAN, latency is non-existent.
- Hitting the web server by IP address (no dns / proxy crazy routing)
- Bootstrap 3.3.7
- jQuery 3.1.1
- PHP 7.1
On my server, with PHP 7+, session_status() always returns PHP_SESSION_NONE.
<?php
if ( session_status() === PHP_SESSION_NONE ) {
session_start();
echo 'Session started<br>';
}
echo 'Session established';
$_SESSION['this'] = 'that';
It looks like you're trying to build a page hit counter. This is how I would do it:
session.php
session_start();
$page = basename($_SERVER['REQUEST_URI'],'.php');
// Check if there is a session variable for this page
// If there isn't one, initialize one to zero
if (!isset($_SESSION[$page])) {
$_SESSION[$page] = 0;
}
$_SESSION[$page]++;
var_dump($_SESSION); // Debug only
some-page.php
require_once 'session.php';
I am using a javascript form script and I want to redirect to an external website. I set the redirect to www.paypal.me but it actually redirects the user to www.mysite.com/www.paypal.me
How can I edit the code below to instead redirect the user to the actual site, not prefaced by my own URL?
var redirect = "www.paypal.me";
...
this.submitOK = function(){
if( redirect == '' ){
showThankYouMessage();
return;
};
try{
if( parent ) parent.location.href = redirect;
}catch(e){
location.href = redirect;
};
}
}
Here you can find a small overview over the redirect methods in js: https://appendto.com/2016/04/javascript-redirect-how-to-redirect-a-web-page-with-javascript/
To a redirect use something like this:
<script>
var locationn = "https://google.com";
window.location = locationn;
I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ?
Thanx in advance
Here is HTML :
<td><input type='checkbox' class='user_status'
id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status'
onclick="userId(<?php echo $data['user_reg_id']; ?>)" />
Here is JS :
<script>
function userId(user_reg_id){
$(document).ready(function(){
var link = "<?php echo base_url();?>" ;
var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1;
$.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st, ajax : 1}, function(data){
alert (st); //showing status 1 and 0 on alert
if (st == 1){
$("#user_status_").prop(":checked", true)
} else {
$("#user_status_").prop(":checked", false)
};
});
});
}
</script>
store checkbox value in database using ajax when you click on it..
also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)
Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.
function isChecked(user_reg_id){
$(document).ready(function(){
$('#user_status_'+user_reg_id).on('click', function () {
if(localStorage && localStorage.getItem(user_reg_id)){
localStorage.removeItem(user_reg_id);
}else{
$('#user_status_'+user_reg_id).prop('checked', true);
}
}
});
}
When user clicks the logout button from the main page, the cookies will be deleted and they will be redirected to window.location = url; . Even if user does not login, but instead clicks logout, they will still be redirected to window.location = url;. My codes are as below, I can't seem to logout even if I click the logout button and I will stay at the main page while being logged in. Can anyone tell what is wrong? I am new to JavaScript and I need help regarding this topic.
$('.logout-btn').click(function(e){
e.preventDefault();
if(isset($_COOKIE['REFERER']) && $_COOKIE['REFERER'] != '') {
window.location = url;
}
else {
$.post(outurl, function( data ) {
}).then(function(r){
$('#popup_ok, .x-close').bind( "click", function() {
window.location = url;
});
if(r.result == 1){
popup_msg('Failed', r.msg);
}
else{
popup_msg('Success', r.msg);
setTimeout(function(){
window.location = url;
},2000);
}
});
}
});
try this code this will execute when user close the tab or close the browser it will automatically destroy session and cookies stored
<body onbeforeunload='destroySession()'>
</body>
<script type='text/javascript'>
function destroySession()
{
$.ajax({
url: 'process/logout.php'
});
}
</script>
logout.php
<?php
session_start();
unset($_SESSION['id']);
header("location:../login.php");
?>
specify the path of your file at place of login.php