session name isnt showing when loading php file - javascript

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);
});
});

Related

Image Download Issue with jquery plugin and php stuff

I have created a QR code generating website. QR code is generated through PHP QR code generator library
by using this code
include_once "../phpqrcode/qrlib.php";
$PNG_TEMP_DIR = '../qrcodeImages/';
if (isset($_REQUEST['text'])) {
$content = $_REQUEST['text'];
$filename = $PNG_TEMP_DIR . 'qr' . md5($content) . '.png';
QRcode::png($content, $filename, 10);
echo $image = "<img class='img' src='qrcodeImages/" . basename($filename) . "'/>";
// $image_src = "qrcodeImage/" . basename($filename);
};
with this ajax call i append the QR code in the required div
$.ajax({
url: "code/single_input_to_qrcode.php",
type: "POST",
data: { text: jquery_plain_text },
success: (parms) => {
$("#downloadPart_img img").remove();
$("#downloadPart_img").append(parms);
}
});
and under QR code div I have placed a download button which is used to download the QR code
for downloading purpose I have used JavaScript library "File Saver"
code
var url = $("#downloadPart_img img").attr('src');
if (url == "img/white-qr-code.png") {
$("#error_msg_div").animate({ "top": "20px" });
error_msg = "Please generate a QR code before download";
error_msg_div.html(error_msg);
} else {
var file_name = url.substring(url.lastIndexOf('/') + 1);
url = "localhost/qrCodeGenerator/" + url;
saveAs(url, file_name);
}
But when user hit download button it show failed to download what kind of issue is that. I thinks this is because when the user hit the download button at the same time the file is saving in the folder so file is not available their at that time.
I have search a lot about that but I am fail to get its solution so now I am on this site to find solution so if some one now how to fix this problem so please help me.
Advance thanks
image of website and failed file at left bottom

window.location.reload(true) reloads page but page needs refreshing to show changes

Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.

Want to load popup on homepage only using jQuery in wordpress

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.

How do I load a javascript file after Jquery.load( )?

I'm navigating through the site by doing this
$('.account-nav a').on('click', function (e) {
e.preventDefault(e);
var url = this.href;
console.log(url);
$('.account-nav a> .account-tab-current').removeClass('account-tab-current');
$(this).children('.account-tab').addClass('account-tab-current');
$('#user-page-content').remove();
$('#user-page-container').load(url + ' #user-page-content').hide().fadeIn('fast');
var url = $(this).attr('href');
if (url != window.location){
window.history.pushState({path: url}, '', url);
}
Problem is, one of the pages contains a script that doesn't get loaded. that page. I also pass in a php variable. It looks something like this:
<div id ='user-page-container>
<div id ='user-page-content>
//content with $variable
<script>
var myVariable =
'<?php
if (isset($variable)) {
echo $variable;
}
//some jquery animation stuff here
?>';
</script>
</div>
</div>
Nothing inside the script get loaded when the html is loaded through jquery.

Can't run server side script using jquery

Firstly, thanks so much in advance for any help you might be able to give me on this!
Right, what I want to do, is to call a php script to run server side, which takes in a single value (which will be an email) and write it to a text file.
This is the .php file that I want run. I haven't added any of the email functionality, but after hours of trying I can't even seem to get it to create a text file and directory. If I run it in the IDE, it runs perfectly, it creates the script and displays the "test me" text at the bottom. However, when It runs from the jquery call, all it does it read the text at the bottom of the file. This is where I call it in jquery:
$(document).ready(function()
{
$("#emailForm").submit(function()
{
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php");
alert("Load called");
//$.post("handleEmailAddresses.php");
});
I've also tried the post function you can see commented out. Nothing works. Here is the php file that is called:
<html>
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
mkdir ($dir, 0777);//This just gives me r/w access to the folder
}
file_put_contents ($dir.'/test.txt', 'Hello File');
?>
Test Text
</html>
Please help, its killing me! Thanks so much!
Try Ajax
$.ajax({
url : '/handleEmailAddresses.php',
});
and if you want to check also:
$.ajax({
url : '/handleEmailAddresses.php',
}).done(function() {
console.log('completed');
});
Use This Script and try
Jquery:
$(document).ready(function()
{
$("#emailForm").submit(function(e)
{
e.preventDefault();
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php", function(response, status, xhr) {
if (status == "error")
{
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
else
{
alert("Load Compleated");
}
});
});
PHP :
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
if (!mkdir($dir, 0)) {
echo('Failed to create folders...');
exit;
}
}
$r = file_put_contents ($dir.'/test.txt', 'Hello File');
if ($r)
echo "Success";
else
echo "Error";
?>

Categories

Resources