appending images from php to document with javascript/jquery - php

<?php
$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
echo json_encode($images);
?>
<script>
jQuery(function(){
var phpvar = '<?php echo json_encode($images) ?>';
jQuery('body').append('<img src="' + phpvar + '"/>');
});
</script>
The top php scans the folder 'images' and echoes all the file pathnames. However i want to use the array formed from this and append it to the document/body to display the images using . But i'm not sure how to pass the php variable '$images' to jquery/javascript

The phpvar that you're creating is actually an array (provided you remove the quotes), so you need to loop through this array and add each image separately, like this:
jQuery(function(){
var phpvar = <?php echo json_encode($images) ?>;
$.each(phpvar, function(id, image){
jQuery('body').append('<img src="' + image + '"/>');
});
});

In my opinion you are wasting processing and a needless framework for simple PHP array processing.
No need for either JSON, JSONEncode or jQuery:
foreach (glob('images/*.{jpg,jpeg,png,gif}',GLOB_BRACE) as $filename) {
echo '<img src=".$filename.'" alt="" />'."\n";
}

<?php
$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
$image_var ="";
foreach($images as $img)
{
$image_var.="<img src=".$img.">";
}
echo json_encode($image_var);
?>
<script>
jQuery(function(){
var phpvar = <?php echo json_encode($image_var) ?>;
jQuery('body').append(phpvar);
});
</script>

Related

Use a jQuery variable in the same file as php echo

I have written the following code in custom.php file (just one file!):
jQuery(function ($) {
$('.price_calc').hide();
$('.lengthm2, .widthm2').keyup(function(){
var priceProduct = <?php echo $priceProduct; ?>;
var lengthM2 = $("#lengthM2").val();
var widthM2 = $("#widthM2").val();
var totalM2 = (lengthM2 / 100) * (widthM2 / 100);
var totalPrice = totalM2 * priceProduct;
$(".m2_customer_total").html(totalM2.toFixed(2));
$(".price_customer_total").html('€'+ totalPrice.toFixed(2));
console.log(lengthM2);
console.log(widthM2);
});
Now in the same file I have added the following code:
<?php
$lengthM2 = $_POST['length'];
$widthM2 = $_POST['width'];
echo do_shortcode( '[gravityform id="2" title="false" field_values="lengthM2='.$lengthM2.'&widthM2='.$widthM2.'"]' )
?>
I can't use the POST variables as I did not post anything.
But how can I manage this works correctly? I tried $.post (jQuery) which not works at all.

PHP: Get next image using Jquery

I have a comics website which loops through all images in a db and displays them as thumbnails.
The user can click on one of those images to see it in normal size on a viewComic.php template.
I'd like to allow users to press left and right arrows to navigate images.
So, my idea is:
pagination.php handles image display on correct pages (by offsetting) by looping through database result array. The user can click on a result (below) to go to that specific image on the viewcomic.php template.
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '">
Now on viewcomic.php, I get the id and image, and display the image
$imgid = $_GET['id'];
$imgpath = $_GET['image'];
<center><img src=".<?php echo $imgpath ?>" /></center>
The user can press left and right arrows to navigate through images...
My goal was to somehow increment the image id to move to the next image, but that doesn't seem to be working...
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
<?php
$count = 0;
$count++;
echo "<img src=" . $imageArray[$count] . "/>";
?>
}
});
});
</script>
Any ideas?
EDIT: I'm going to go through an image array passed in from pagination.php.
So, in my viewcomic.php file, I've updated my jquery script (see above).. but the jquery doesn't seem to like the embedded php, even though it's all in a php file.
Here's a picture of page source vs code:
Here is what i would do:
assuming that an imagepath is surrounded by quotes:
echo $imageArray[0]; // 'imagepath/image'
Script:
<script type="text/javascript">
var imgArray = [<?php echo implode(',',$imageArray) ?>];
// now the image array have the list of all your images.
$(document).ready(function() {
var img = document.getElementById("theImage");
imgIndex = 0;
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
img.src = imgArray[imgIndex++]
}
... /* Logic to check if at the end of imageArray */ ...
});
});
</script>
The Html:
<center><img src="" id="theImage"/></center>
How about:
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
var nextId = $_GET['id'] + 1;
window.location = "./templates/viewcomic.php?id=" + nextId;
}
});
});
In this case your page is submit on every request, You can also handle this at client site.
Click link to see demo about rotate link using JavaScript. : Link Rotate using javascript

Pass a php var to jQuery Function

How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.

Passing var from php to javascript

I try to do something pretty strait... getting php value to javascript
here is the page
here is the code..
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php $imagepath; ?>
alert (whatisthepath);
</script>
ALWAYS getting UNDEFINE.... why ?
--
Final wordking optimized code :
alert ("<?php echo $_REQUEST["path"]; ?>");
Missing: quotes around the var, php output to js var, semicolon after var setting:
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = "<?php echo $imagepath; ?>";
alert (whatisthepath);
</script>
All strings in JavaScript need to be surrounded with quotes. For example:
var whatisthepath = "<?php $imagepath; ?>";
The other issue is that you are not actually printing the string. All the above line of code will result in is an empty set of quotes. The correct way to do it would be to echo the imagepath
var whatisthepath = "<?php echo $imagepath; ?>"
For exactly this purpose, PHP offers the shorthand notation of <?= ... ?>. To output to value of the variable $imagepath, you can use <?= $imagepath ?>. For this to work, the short_open_path ini variable must be set to true. This may not be the default of your web server.
So, this turns the code into
<?php
ini_set('short_open_tag', TRUE);
$imagepath = SOME_VALUE;
?>
<script language="javascript">
var whatisthepath = "<?= imagepath ?>";
alert(whatisthepath);
</script>
Changing the ini value may not be convenient if it's just about a few variables, but if it happens more often in the code, I tend to find it make things more readable.
You forgot to add an echo or print statement in front of your $imagepath
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo $imagepath; ?>
alert (whatisthepath);
</script>
PHP is a serversided language while javascript is a client side language. Which means you have to threat it the same way you would threat HTML.
For example:
<div><?php echo $content; ?></div>
Hopefully this will give you a better understanding...
You can use json_encode() to ensure that the variable is properly escaped and quoted etc. for javascript. e.g.:
<?php $imagepath = $_REQUEST["path"]; ?>
<script language="javascript">
var whatisthepath = <?php echo json_encode($imagepath); ?> ;
alert (whatisthepath);
</script>
You should use to ensure that the variable has correct JS syntax.
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo json_encode($imagepath); ?>;
alert (whatisthepath);
</script>

var transfert between php and javascript

I like to get a dir listing in php
glob("*.jpg");
or
$dir = '.'; //requested directory to read
$notthat = array('.', '..'); //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include
so i like to send that array to a javascript like that (slides = $listedfiles)
function startSlideshow(slides) { .. do something..}
What is the best way to do that ?
json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:
var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}
you can always just do an echo of it to a javascript :
echo ' <script type="text/javascript">
var filelist = [];
';
foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}
echo "</script>";
PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:
<script type="text/javascript">
var slides = [];
<?php
foreach ($listedfiles as $file)
{
echo "slides[] = '" . addslashes($file) . "';\n";
}
?>
// ... do js stuff
</script>
Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.

Categories