var transfert between php and javascript - php

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.

Related

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

appending images from php to document with javascript/jquery

<?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>

reading Json from PHP with javaScript

My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});

Syntax error help

I seem to have a syntax error and can't see it myself, could someone run over it for me please?
Thanks.
<script>
var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>
Because you got some answers that intended to show you how to improve your code, but actually don't do so (IMO), here is my attempt:
<?php
$acurl = array();
$acurl[$request_data['friendship_id']] = sprintf('sn-include/create_bond_accept.php?friendship_id=%s&friend_id=%s', $request_data['friendship_id'], $fromuser['id']);
?>
<script>
var acurl = <?php echo json_encode($acurl); ?>
</script>
I would not create dynamic variable names. This code would create a JS object, where the properties are the friendship IDs, something like:
{
'42': 'sn-include/create_bond_accept...'
}
You can access these URLs more easily from JavaScript than if you have dynamic variable names.
David, on the bright side, you don't have a syntax error.
If you're developing PHP, I would recommend two things:
Get a better IDE. Dreamweaver is TERRIBLE for working with PHP. I recommend NetBeans (it's awesome and free).
Start breaking up your code into chunks. The big ball of html and PHP is hard to debug.
Check this out:
<?php
// prepare output
$segment = '?friendship_id=' . $request_data['friendship_id'];
$segment .= '&friend_id=' . $fromuser['id'] . '";' . "\n";
$acurl = 'var acurl_' . $request_data['friendship_id'];
$acurl .= ' = "sn-include/create_bond_accept.php';
$acurl .= $segment;
$dnurl = 'var dnurl_' . $request_data['friendship_id'];
$dnurl .= ' = "sn-include/create_bond_deny.php';
$dnurl .= $segment;
?>
<script type="text/javascript">
<?php
echo $acurl;
echo $dnurl;
?>
</script>
Use here doc instead:
<?php
echo <<<JS
<script>
var acurl_{$request_data['friendship_id']} = "sn-include/create_bond_accept.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
<script>
var dnurl_{$request_data['friendship_id']} = "sn-include/create_bond_deny.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
JS;
?>
See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

How do I use PHP to supply info to JavaScript?

I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).

Categories