php: make array from pictures in a folder and display them interchangeably? - javascript

The following code is supposed to make an array from pictures found in a directory that end in .png using php, then allow buttons to change the pointer on the array and allow the page to display the current picture that the pointer is on. This doesnt seem to be working at all. Am I doing this correctly?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
img {float:left; }
</style>
</head>
<body>
<?PHP
$pages = array ();
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
foreach($images as $image) {
$pages[] = $image;
}
?>
<?PHP
echo '<img src="'.current($pages).'" class="photo"/>';
function shownext() {
$mode = next($pages);
}
function showprev() {
$mode = prev($pages);
}
function showfirst() {
$mode = reset($pages);
}
function showlast() {
$mode = end($pages);
}
?>
first
previous
next
last
</body>
</html>

onclick will allow you to call a javascript function, while your showprev...showlast functions are all php functions. They are not available in javascript's scope.
Also, in your php code:
You are closing the loop right after $pages[] = $image, I think you intend to display (print/echo) all images.
You don't need a loop to copy $pages to $images. You can easily copy it: $pages = $images.
You should be aware that current only makes sense inside a loop and you are calling it after loop is closed.
I think though, that you are confusing server-side (i.e. php) and client-side (i.e. javascript) execution environments.

onclick , uses to trigger javascript functions.

You cant directly put your php functions on onclick="" events. Alternatively, if you want to use jQuery, you could use $.ajax to request the values on PHP. From there, after you got the image paths, manipulate the next, prev, first, last on the client side. Consider this example:
<?php
if(isset($_POST['getimages'])) {
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
// collect the images
foreach($images as $image) {
$pages[] = $image;
}
echo json_encode($pages);
exit;
}
?>
<img src="" alt="" id="images" width="200" height="200" />
<br/>
First
Previous
Next
Last
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var current_pointer = 0;
var images = [];
$.ajax({
url: 'index.php', // call the php file that will process it, i just used this in the same page
type: 'POST',
dataType: 'JSON',
data: {getimages: true},
success: function(response) {
// after a successful response from PHP
// use that data and create your own array in javascript
images = response;
$('#images').attr('src', images[current_pointer]);
}
});
// simple pointer to navigate the array you got from PHP
$('a.navigate').on('click', function(){
var current_val = $(this).attr('id');
switch(current_val) {
case 'first':
current_pointer = 0;
break;
case 'last':
current_pointer = images.length-1;
break;
case 'next':
current_pointer = (current_pointer >= images.length-1) ? images.length-1 : current_pointer+1;
break;
case 'previous':
current_pointer = (current_pointer < 0) ? 0 : current_pointer-1;
break;
}
$('#images').attr('src', images[current_pointer]);
});
});
</script>

The problem is echo '<img src="'.current($pages).'" class="photo"/>';
This will get echoed once, no matter howoften you change $pages afterwards. You also can't call PHP functions with JavaScript's onclick.
PHP will generate the page on server side! On a fully laoded page, most interaction with the user is done via JavaScript.
To achieve your desired result, you have to export the array to JavaScript and change the image src via JavaScript, a little research will help you.

Related

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

How to load php vars from an external file with javascript

I had this code inside the <div id="chtmsg"> on a page that shows a messenger...
PHP :
if($perguntas){
for($c=0;$c<count($perguntas);$c++){
$perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
$hora = substr($perguntas[$c]->hora, 0, 5);
echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
$pergunta->marcaRespLida($perguntas[$c]->id);
}
}
}
It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...
HTML :
$(document).ready(function () {
setInterval(function() {
$.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
$('#chtmsg').html(result);
scTop();
});
}, 3000);
});
But its shows the error inside de div...
Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3
I tested other codes inside the msg.php file and works ok without variables...
Just a thought...
Your first line in PHP
if($perguntas){
Should perhaps check if defined like so
if(isset($perguntas)){
My suggestion explained in another answer here
For better code, You should preferably use:
if (isset($perguntas) && is_array($perguntas)){

Automatically update with AJAX

I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

Refactoring 3 small bits of PHP function into JS - array, if empty and matching url?

I'm not much of a JS person but I'd like to know how to run my PHP into JS. How can I do the following using Javascript only?
// 1. Getting the request
<?php if($_GET["slider"]=="1"){ ?>
$(".class1 a").click()
<?php } ?>
<?php if($_GET["slider"]=="2"){ ?>
$(".class2 a").click()
// 2. Matching the URL and setting an active class on the list item
<li>My Page</li>
// 3. Nav array and If empty
<?php
$navigation = array(
'previous' => 'page1.php',
);
if (isset($navigation['previous']))
{
?>
<div class="prev">
<a href="<?php echo $navigation['previous']; ?>">
<span class="previous-icon"></span><span>Previous</span>
</a>
</div>
My attempt after Googling..
<?php if(var _GET["slider"]=="1"){ } if(_GET["slider"]=="2"){ if (strrpos(var _SERVER['REQUEST_URI'], 'my_page') !== false ) {} var navigation = {
'previous' : 'page1.php',
};
if ((navigation['previous']))
{
you can get "GET" values (query string) like in this Answer
window.location.href.indexOf("my_page") != -1 , search for window.location and indexOf for further explanation
check code
var navigation = {previous:"page1.php"};
document.write('<a href="'+navigation["previous"]+'">....');`
Arrays can't have string indexes in js, you need to use objects;
you can also use navigation.previous instead.
you can't mix js and html like you do with php, you have to "echo" everything using document.write or other DOM manipulation functions. For further help on these topics, search the bold parts.
To answer your three questions:
1: Clicking something if a variable is in the URL (i.e. /page.php?slider=1): Check out this page, which details how to retrieve variables from URLs in jQuery. In short, you can do something like,
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
to get the variables from a URL, and from there you can check if a variable is set by asking getUrlvars()['slider'] == 1.
2: Matching the url and setting a class as active: You can do something like
if (window.location.href == 'http://www.example.com/page.php') {
$('a').addClass('active');
}
3: If you're looking to create a dynamic list of links using Javascript arrays, you could do something like this:
var myLinks = {
"link_1_title": "http://www.example.com",
"link_2_title": "http://www.stackoverflow.com/"
}
$.each(myLinks, function(key, val) {
$('.navbar').append('' + key + '');
}
For a more detailed explanation about jQuery.each, please see the jQuery doc page.
It sounds like you've got an unholy alliance here of PHP drawing the JS and then the JS doing things. It's a recipe for disaster. Your PHP should pass your data to your JS and then let the JS do the work. Don't mix logic. Have a clean handoff.
<script>
var something = <?php echo $var ?>;
myclass = new someClass(something);
</script>

Categories

Resources