how to write php base_url() in js file - javascript

I want to send base_url from Controller Book to book.js
This is my function in book.js
function loadPage(page, pageElement) {
// Create an image element
var img = $('<img />');
img.mousedown(function(e) {
e.preventDefault();
});
img.load(function() {
// Set the size
$(this).css({width: '100%', height: '100%'});
// Add the image to the page after loaded
$(this).appendTo(pageElement);
// Remove the loader indicator
pageElement.find('.loader').remove();
});
// MY PROBLEM is here !!! Load the page
// img.attr('src', '../../_library/book/samples/magazine/pages/' + page + '.jpg');
img.attr('src', '<?php echo base_url($source) ?>' + page + '.jpg');
loadRegions(page, pageElement);
}

You cannot use php commands in js files. But instead you can define a variable between script tags in the php file. For example:
example.php
<script>
const EXAMPLE_VAR = '<?php echo base_url($source);?>'
</script>
And you can use it in js file like this:
img.attr('src', EXAMPLE_VAR + page + '.jpg');

Related

session name isnt showing when loading php file

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

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

looking to Work around the 403 error with php script

I have been using JavaScript to retrieve my images from a directory and on local-host this works just fine but now I am running it on a remote sever I get the 403 Forbidden Error, I know why this is but I am looking for a way around it, keeping my Java functioning much the same, so I was thinking if I put an index.php in the gallery folder and called it with a path and have it return a file list back to my JavaScript and a lough it to carry on.
How would I go about this as I am not very good with PHP at the moment? Thanks.
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var dir_path = $(this).data("albumid");
LoadGallery(dir_path);
return false;
});
});
function LoadGallery(dir_path) {
$.ajax({
url: dir_path,
success: function(data) {
$(".image-container").empty();
$(data).find("a:contains(.jpg), a:contains(.png), a:contains(.jpeg)").each(function() {
this.href.replace(window.location.host, "").replace("http:///", "");
var file = dir_path + $(this).text();
$(".image-container").append($("<a href='javascript:;' class='thumb' data-src='" + file + "'><img src='" + file + "' title='Click to enlarge' alt='#'/></a>"));
if ($(".image-container").children("a").length === 30) {
return false;
}
});
$(".image-container").append("<strong><p>Click on a thumb nail to show a larger image.</p></strong>");
$(".thumb").bind('click', function() {
var Popup = "<div class='bg'></div>" + "<div class='wrapper'><img src='<img src=''/>" + "<label href='javascript:;' class='prev-image'>«</label><label href='javascript:;' class='next-image'>»</label><a href='javascript:;' class='close' title='Close'>Close</a>";
var Img = $(this).attr("data-src");
$("body").prepend(Popup);
$(".bg").height($(window).height() * 4);
$(".wrapper img").attr("src", Img);
$(".prev-image").bind('click', function() {
var prev = $(".image-container").find("img[src='" + Img + "']").parent().prev('a').find("img").attr('src');
if (!prev || prev.length === 0)
return false;
else {
$(".wrapper img").attr("src", prev);
Img = prev;
}
});
$(".next-image").bind('click', function() {
var next = $(".image-container").find("img[src='" + Img + "']").parent().next('a').find("img").attr('src');
if (!next || next.length === 0)
return false;
else {
$(".wrapper img").attr("src", next);
Img = next;
}
});
$(".close").bind('click', function() {
$(this).siblings("img").attr("src", "")
.closest(".wrapper").remove();
$(".bg").remove();
});
});
}
});
}
</script>
Original why are you getting the 403 error? returning a file(name) list from php to your scripts probably isn't going to work around this error, because the javascript would ultimately be making the same request.
on the other hand if you know that you have access to the image files from the server-side there are a few things you could do, like return the binary value of the image (javascript can take this) or generating a close of the file.
Update
if the server allows it, you can use the exec command in php to return a list of files from the directory: eg
\<\
<?php
jpgs = exec('ls /your_directory_here');
echo json_encode(jpgs);
?>
if they don't allow exec(), which they might not, you could try...
http://www.w3schools.com/php/func_directory_readdir.asp
does that help?

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.

Count images in directory from js file

I have an image loading function in a js file.
It loads images from 1.jpg to a specified number (let's say 20).
What I would like to do instead of specifying a number, is find out how many images are in the folder and then use that as the specified number.
I know it is possible using GLOB in PHP, but AFAIK you can't use PHP in a js file?
function loadpics(url){
var txt,i,j;
j=20
//j=count(glob("images/" + url + "/*",GLOB_BRACE)); PHP file count here.
txt= "<span id=\"lar\">«</span><img id=\"main-img\" src=\"images/" + url + "/1.jpg\"/><span id=\"rar\">»</span><div id=\"scroller\">";
for (i=1;i<j;i++)
{
txt += "<img src=\"images/" + url + "/t/" + i + ".jpg\"/>";
}
document.getElementById("sidebar-b").innerHTML=txt + "</div>";
}
So how can I get the number of files from the url I pass to my loading picture function?
Or is there a better way?
Instead of relying on the pictures being sequentially ordered, use a foreach loop or create a script that merely echos the filenames as JSON for javascript to request
<?foreach(array_map('basename',glob('memes/*.jpg')) as $value){?>
<img src='memes/<?=htmlentities($value,ENT_QUOTES|ENT_XML1|ENT_SUBSTITUTE,"UTF-8",true)?>' style='height:200px;'/>
<?}?>
or
<?
if(isset($_GET['pic_list'])){
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array_map('basename',glob('memes/*.jpg')),JSON_PRETTY_PRINT);
exit;
}
?>
<div id='pic_list'></div>
<script>//<![CDATA[
(()=>{
var
xhr=new XMLHttpRequest()
,list=document.getElementById('pic_list');
xhr.onload=()=>{
var frag=new DocumentFragment();
xhr.response.forEach((v)=>{
var img=document.createElement('img');
img.src='memes/'+v;
img.style.height=200;
frag.appendChild(img);
});
list.appendChild(frag);
};
xhr.open("GET","?pic_list");
xhr.responseType="json";
xhr.send();
})();
//]]></script>

Categories

Resources