how to insert a php code in a jquery function - javascript

i'm coding a php site to serve on file sharing . i had a problem with hiding the delete file option from users and showing it for site admin , the actual logged in user name is stored in a php session so hiding or showing the delete option will be used in php condition .
the problem is the php code never worked to add the "hidden" option on delete img tag .
in 1st step, js, jquery and php code were separated in two files, so i had to copy jquery code in index.php (main page) since i had no other option to grab the logged in user from php session to js file.
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if (scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length - 1];
icon = '<span class="icon file f-' + fileType + '">.' + fileType + '</span>';
var x = f.path.replace(/\/\/+/g, '/');
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li><img src="assets/supp.png" height="42" width="42" id="logo" onclick=del("'+encodeURIComponent(x)+'") if($_SESSION['username']!='info') {?> hidden <?php } ?>>');
file.appendTo(fileList);
});
}

<?php if($_SESSION['username']!='info') echo 'hidden' ?>
You need to put your php code inside php tags. You had syntax errors in your example code.
That way if your if statement is true it will show the "hidden" parameter causing your html element to be invisible.

Related

PHP breadcrumbs with list of paths

I have a breadcrumbs script that divides the URL with /and links each one to the same path. However, I am facing two issues:
I have an older website which didn't have index.php in many
folders, so I need to add an array for which file to go to for that folder.
Some folders could have the same name in different locations.. so there could be a path like example.com/something/Samename, and another like example.com/another/path/Samename, and I need to set the title that shows in the breadcrumbs, so it's meaningful more than the path names.
So I want to add something like an array to tell it if the path is /another/path/Samename link to thisfile.php, and if it is the other folder link to another file.. etc., and if there is no array for that path then it links normally to the foldername, which means it has index.php file.
My current script is:
var path = "";
var href = document.location.href;
var s = href.split("/");
for (var i=2;i<(s.length-1);i++) {
path+=""+s[i]+" / ";
}
i=s.length-1;
path+=""+s[i]+"";
var url = window.location.protocol + "//" + path;
document.writeln(url);
//-->
And this another script that does the same:
//this is a file named 'functions.php'
<?php
function breadcrumbs(){
$bread = explode('/', $_SERVER['PHP_SELF']);
$url = '/';
$returnString = "<span class='bc0'><a href='$url'>home</a>";
for($i=1;$i<count($bread)-1;$i++){
$url.=$bread[$i].'/';
$returnString .= " |</span> <span class='bc$i'><a href='$url'>$bread[$i]</a>";
}
echo $returnString.'</span>';
}
?>
//in header of path
<?php include ( $_SERVER['DOCUMENT_ROOT'] . 'functions.php'); ?>
//where the breadcrumbs show
<?php breadcrumbs(); ?>

Title Tag Nested inside itself with jQuery PHP Load

I have a dynamic site that loads only the body when a usr clicks a page. I am trying t change the title tag, but am getting no luck.
HTML:
<head>
// Title tag is contained in the php file
<?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?>
</head>
JavaScript/jQuery:
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
var baseurl = "http://localhost/offstreams/";
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
//!!!!!!!!!!!!!!!!!!!!!
// THIS IS THE PROBLEM
//!!!!!!!!!!!!!!!!!!!!!
$('title').empty().load(pageurl + "> title > *");
// Push the URL state
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
}
});
A Snippet of PHP code:
//Band page title tag
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
An example output on actual load would be Count to Four | Offstreams, which is what I want.
When I do the ajax load, the website works, but the title tag gives the default url like localhost/offstreams/etc... and the title tag turns into
<title>
<title>Count to Four | Offstreams</title>
</title>
Does anyone know why?
It looks like you're doubling up on title tags there, the $('title').empty() bit will be leaving the previous ones there.
Try putting the title tags in your initial html:
<head>
// Title tag is contained in the php file
<title><?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?></title>
</head>
And removing them from your php:
echo $band_name . " | " . "Offstreams";
I don't understand the reason for outputting the title in a loop since there is only one per page, unless I am missing something in your code. Seems like it needs to be outside.
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
}
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
In regards to your JQuery script, keep this in mind from the .load() documentation:
jQuery uses the browser's .innerHTML property to parse the retrieved
document and insert it into the current document. During this process,
browsers often filter elements from the document such as <html>,
<title>, or <head> elements. As a result, the elements retrieved by
.load() may not be exactly the same as if the document were retrieved
directly by the browser.
In other words, what you're doing may not work properly all the time with all browsers. With that in mind, give this a try.
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
// Give this a try
$(pageurl).load(pageurl, function() {
$('title').load('title', function() {
document.title = $(this).text();
});
});
// Push the URL state
if(pageurl !== window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});

How to make a slideshow banner in html?

I want to make my banner changed automatically just like a slideshow. The banner I took from a folder and it can read all banner in that folder and display it on a website automatically changes. I already make it to read all banner and display it on the website, but it kind of random image, not changed except if I reload the page. This the code:
<?php
$imglist='';
//$img_folder is the variable that holds the path to the banner images.
// see that you dont forget about the "/" at the end
$img_folder = "images/";
mt_srand( (double)microtime()*1000 );
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and ads them to a list (see below how to display flash banners)
while ( $file = $imgs->read() )
{
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
}
closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist); $no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no); $image = $imglist[$random];
//display image
echo '<img class="img-responsive" src="'.$img_folder.$image.'" border=0>';
?>
And how to make that PHP into HTML? if I change the extention into html, the banner div show the code not the images. Thanks.
The psuedocode for what you're doing would go something like:
load images from a directory into an array
on page load select a random image from image array
display first image
every X seconds display another image from image array
to display properly, your php file needs to be loaded/served from a web server. To do this, deploy your php file to your web server and then test it out.
an example of a banner I created a few years agao, that is similar to what you are after, is here
First, make your PHP echo out a hidden <input> element, with value containing the JSON string of image paths. Using your code, something like:
<?php
$out = " /* Beginning of your page code */ "
$imgJSON = json_encode($imglist);
$out .= '<input id="bans" type="hidden" value="' .$imgJSON. '" />';
$out .= " /* Rest of your page code */ "
echo $out;
die();
Then, you can use the example below to swap the images in the banner div. I demonstrate a very simple animation, just to show how it is done.
jsFiddle Demo
HTML:
<!-- Not req if you echoed out a hidden input via PHP:
<input type="hidden" id="bans" value='["300/49","300/51","297/50","298/51"]' />
-->
<div id="banner"></div>
javascript/jQuery:
var i = $('#bans').val();
var j = JSON.parse(i);
var max = j.length - 1;
var cnt = 0;
var timerId = null;
function swapBannersTimer() {
doSwap();
timerId = setTimeout(swapBannersTimer, 3000);
}
function doSwap(){
var str = 'http://placekitten.com/' + j[cnt];
$('#banner')
.html('<img class="far_right" src="'+str+'" />')
.promise()
.done(function(){
$('img').animate({
marginLeft: '0px'
},500);
});
cnt = (cnt < max) ? cnt+1 : 0;
}
swapBannersTimer();
**CSS:*
#banner{width:300px;height:52px;overflow:hidden;}
.far_right{margin-left:300px;}
NOTE: Because this example uses the jQuery library, you must include it on your page -- usually between the DIV tags, like this:
<head>
<!-- other stuff in head -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
If you use a CDN to load jQuery, as in the above example, it is probably already be pre-loaded from other websites.
If you want some fast lessons on jQuery, find free video tuts here:
https://www.thenewboston.com/videos.php?cat=32
or at
https://phpacademy.org/videos/jquery-basics

Error when sending html source from javascript to PHP

I am using the following to encode the html source of a ckeditor in a web application.
var updateString = app.getValue('wysiwygHomePage');
var encodedString = encodeURIComponent(updateString);
alert(encodedString);
app.httpRequest("www.xxxx.com/techy/savealldata.php", "GET", function(data, error, httpResponse){
alert(data);
},
{
"updateType":"homePage","updateString":encodedString}, "String", {}, {});
}
Then at the PHP end I am using :
<?php
$updateType = $_GET["updateType"];
$updateString = $_GET["updateString"];
$updateString2 = urldecode($updateString);
echo 'success here '.$updateType .' '.$updateString2 ;
?>
I am adding some coloured tex and the html source for this is:
<p>
<span style="color: rgb(255, 140, 0);">123</span><br />
</p>
<p>
This works okay until I cut and paste more than 32 times.
I then just get error returned from the PHP call.
I presume there are to many chars arriving at the PHP end ???
Any ideas why this is happening ?
Mr WARBY.
UPDATED PHP Code.
<?php
include 'dbdata.php';
$updateType = $_POST["updateType"];
$updateString = $_POST["updateString"];
$updateString2 = urldecode($updateString);
//echo 'success here '.$updateType .' '.$updateString2 ;
if($updateType === 'homePage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 12";
//echo $query5;
echo 'Home Page Updated 2';
mysql_query($query5);
}
if($updateType === 'instructionPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 13";
echo 'Instruction Page Updated 2';
mysql_query($query5);
}
if($updateType === 'FAQPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 14";
echo 'FAQ Page Updated';
mysql_query($query5);
}
?>
There are a lot of variables in play here. You need to change your debugging strategy. Instead of testing end to end each time try isolating each component.
In Javascript, call "app.getValue('wysiwygHomePage')", encode the string, decode the string, and put it right back in the editor. Do that in a loop until you can determine if the client-side is mangling anything.
If not, try encoding a complicated string in Javascript, sending it to a PHP script that decodes/re-encodes and echos it back. Do that in a loop several times.
If you still haven't found the problem try making a PHP script that takes a complicated string, INSERTS it, SELECTs it, UPDATEs it in a loop to see if you database encoding or escaping is affecting it.
If at any point you find the string changing when it shouldn't you've probably found your problem.

Display final results on the same page from a dynamic drop down menu

I have a multiple drop down that goes from Country/State/city/destination.
What I want this plugin to do next, is once the destination menu is selected, the page will automatically display some general information about that destination on the same page without reloading.
The general info is in the same table as my destination drop down menu is, but under different columns.
So how can I get this information to display its self possibly in a text box or something similar only when the final distention menu is selected.
Here are some parts of my code thus far, I don't believe posting everything is necessary and might be a little confusing. PS-I am a beginner.
This is an example of my javascript which calls from my ajax.php file for the array to populate the drop down menu...
jQuery(".wrap").on('change', '#city', function() {
var querystr2 = 'cityid=' +jQuery('#city :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/Destination_Drop_Down_Menu/ajax.php", querystr2, function(data) {
if(data.errorcode ==0){
jQuery('#descbo').html(data.chtml)
}else{
jQuery('#descbo').html(data.chtml)
}
}, "json");
});
This is part of my ajax.php file that previous example of jQuery is pulling information from.
$city_id = isset($_POST['cityid']) ? $_POST['cityid'] : 0;
if ($city_id <> 0) {
$errorcodeD = 0;
$strmsg = "";
$sqlD="SELECT * from destination WHERE IDCity = ". $city_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
$contD=mysql_num_rows($resultD);
if(mysql_num_rows($resultD)){
$chtmlD = '<select name="destination" id="destination"><option value="0">--Select Destination--</option>';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<option value="'.$row['IDDestination'].'">'.$row['name'].'</option>';
}
$chtmlD .= '</select>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
}else{
$errorcodeD = 1;
$strmsg = '<font style="color:#F00;">No Destination available</font>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$strmsg));
}
And MY html section that would display everything.
<h2>Destination</h2>
<div class="wrap" id="descbo">
</div>
So basically what ever destination the user chooses, the specific information for that destination will render its self on the screen in separate boxes or text areas.
Thank you!
So, if I understand correctly, you want your php script to return data from your destination table when a particular destination is selected. You said you don't want the page to reload, but I'll assume you're OK with issuing another AJAX request to the server. If that's the case, you can simply create another delegated jQuery handler for the destination <select>:
jQuery(".wrap").on('change', '#destination', function() {
var data = {destinationid: this.value};
jQuery.post("url/to/script.php", data)
.done(function(response) {
jQuery('#descbo').html(response.html);
});
Then, in your PHP, you could have something like this:
$destination_id = isset($_POST['destinationid']) ? $_POST['destinationid'] : 0;
...
$sqlD="SELECT * from destination WHERE ID = ". $destination_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
if(mysql_num_rows($resultD)){
$chtmlD = '<div class="destination">';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<p>' . $row['whatever'] . '</p>';
}
$chtmlD .= '</div>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
} else {
...
}
That will replace your original destination <select> with a div containing the destination description (or whatever the content is). If you don't want to replace the select, you could simply have the JS update a different element on the page, e.g.
jQuery('#some_other_element').html(response.html);

Categories