Reload function that make fancybox appear - javascript

i (with the help of user) already did one page that has a function to read a value on a txt file and if it's "1" a fancybox (version 2) with a iframe appear.
Code ReadAndAppear.php
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec;
if($valrec == 1){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$.fancybox({
href: "alert.php",
type: "iframe"
});
}); //ready
</script>
<?php
}; // closes if
?>
So, to try that this function/page reload (5-5 seconds) to appear the fancybox if the valrec is "1" I create a new page, lets call it index.php
index.php code
head
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#ReadAndAppear').load('ReadAndAppear.php').fadeIn("slow");
}, 50000); // refresh every 10000 milliseconds
</script>
body
<div id="ReadAndAppear"></div>
unfortunately this code doesn't make the fancybox appear on the index.php when valrec=1. this algorithm only refresh and make appear images, echos etc, but not fancybox.
How can i make refresh and appear on the index.php or even better on ReadAndAppear.php
thanks

You would be better off storing the fancybox function in a separate JS file. Then you could call for it in the callback of the ReadAndAppear load function -
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#ReadAndAppear').load('ReadAndAppear.php').fadeIn("slow", function(){
$.getScript('fancybox.js'); // gets and runs script
});
}, 50000); // refresh every 10000 milliseconds
</script>
In ReadAndAppear.php you can make changes to load the same script -
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec;
if($valrec == 1){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$.getScript('fancybox.js');
}); //ready
</script>
<?php
}; // closes if
?>
Now put the script in its own file facybox.js
$.fancybox({
href: "alert.php",
type: "iframe"
});
Honestly doing it this way has both good and bad points though. I think, as I said before in the comments, that I think your logic needs a little rethinking. I shouldn't have to use $.getScript() if my code is organized well and included in the project differently. It would be much easier to maintain.

Moving the script into index.php, I would do something like this :
<script type="text/javascript">
var myRefresh;
jQuery(document).ready(function($){
myRefresh = setInterval(function(){
<?php
$lines = file('alerta.txt');
$valrec= $lines[0];
echo $valrec; // do you need this echo ?
if($valrec == 1){
?>
$.fancybox({
href: "alert.php",
type: "iframe"
});
<?php } else { ?>
clearInterval(myRefresh); // cancel interval if $valrec != 1
<?php
}; // closes if else (php)
?>
},5000); // setInterval
}); //ready
</script>

Related

How to call a javascript function script from php

<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>
<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>
This code is heavily simplified down but the key values are presented. I am trying to run a Javascript function at the bottom of the code from php. In the full code, the php echoes that script when something occurs. I have tried similar code:
echo "<script> alert('Error!') </script>";
This works but I'd rather create my own alert message which occurs in the top right corner of the page. The div is set to display: none, but I'm trying to run call the function which sets the display: block. All the css is dealt with and I have tested it works with a button.
I am running my code on XAMPP apache mysql. This is the error type when loading the page:
Uncaught ReferenceError: error_warning is not defined
at account.php:1
What I've gathered is that as the php is running server side, that the function is not defined so it can't see it hence returning the error. I've tried several solutions like putting the script before the php and they haven't worked.
Can anyone help?
Thanks
The solutions for this problem are...
Call function after it is defined.
for this you can use some server side variable to active the function call at the end of the page.
<script> function popAlert(errorType){//do something} </script>
<?php if($error == 1) echo "<script>popAlert(1);</script>";?>
Put your function in a separate .js file and include it in your page.
<?php
if($error == 1) echo "<script>popAlert(1);</script>";
?>
<script src="errors.js"></script>
Use Ajax to get response from .php file and then determine what needs to be popped up
Ex:-
$.post("url", "data", function(data, status){
if(status == "success"){
if(data == 1) popAlert(1);
if(data == 2) popAlert(2);
}
});
Extras
I recommend you to use Sweat alerts reference here
Ex:-
function popAlert(type){
if(type == 1){
Swal.fire({
icon: 'success',
title: 'You did it...!'
})
}
if(type == 2){
Swal.fire({
icon: 'error',
title: 'Oops, something went wrong...!'
})
}
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10.10.1/dist/sweetalert2.all.min.js"></script>
<h1>Click on buttons to pop alert</h1>
<button onclick='popAlert(1)'> success </button><br/>
<button onclick='popAlert(2)'> error </button><br/>
For any queries comment down.
There are multiple options to do this. Ajax or a simple echo. But for your problem, it is enough to simply add the onload function to the script echo.
<?php
echo "<script type='text/javascript'>window.onload = () => {error_warning('Error!')}; </script>";
?>
Another possible option would be to call the function after it has been declared.
<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>
<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>

showing a loading message before appending

I don't know much about jQuery/Javascript but I have this code that appends a data.php file into a div once the page has finished loading,
but that php file is a bit big and takes 2-4 seconds to appear on the div after page loaded,
How do I show a message inside the div saying (loading..) or a loader gif image during that 2-4 seconds while the php file is getting ready? here is my code:
<?php $u=$_GET['id'];?>
<script type='text/javascript'>
var get = "<?php echo $u; ?>";
$(document).ready(function() {
$.get("/data.php?id="+get, function(data) {
$("#c").append(data);
}, 'html');
});
</script>
The easiest would be to just write, then rewrite the .html()
<script type='text/javascript'>
var get = "<?php echo $u; ?>";
$(document).ready(function() {
$("#c").html("<div class='tmp-loading'>Loading....</div>");
$.get("/data.php?id="+get, function(data) {
$("#c").html(data);
}, 'html');
});
</script>
If you have to append() instead of rewrite html(), then you can hide the loading tag when the data comes in.
<script type='text/javascript'>
var get = "<?php echo $u; ?>";
$(document).ready(function() {
$("#c").append("<div class='tmp-loading'>Loading....</div>");
$.get("/data.php?id="+get, function(data) {
$("#c .tmp-loading").hide();
$("#c").append(data);
}, 'html');
});
</script>

Passing PHP variable via AJAX to PHP variable in another DIV

I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX. I want my website to display the results of Python script. I can do that.
The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes. Usually the user has to keep reloading the page to get a current status. I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.
The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.
If possible, one PHP file (index.php). Here is the skeleton of what I'm looking to do. My get_status function works, but I'm at a loss on the rest of it.
Thank you.
EDIT: Code updated with minor tweaks spotted by the commenters.
<html>
<body>
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
var java_status = <?php echo json_encode(get_status) ?>;
// I have no idea how to pass a variable from PHP thru javascript to PHP on the
// same page. Trying to pass on results of get_status function every 5 seconds.
setInterval(function(){
$.ajax({
url: "index.php"
type: "POST"
dataType: "json"
data: ({status: java_status}),
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
<div id="status_div">
<?php
$new_status = json_decode(data);
?>
// I have no idea how to get that status variable here.
The Garage Door Status is: <?php
echo $new_status;
?>
</div>
</body>
</html>
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:
PHP Script - php_python.php
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
get_status(); // execute the function
?>
HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)
You also need to separate <script> tags, using one to load the jQuery library and another to describe your JavaScript functions.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){ // you need a document ready handler if you put the script at the top of the page
setInterval(function(){
$.ajax({
url: "php_python.php",
type: "POST",
dataType: "text",
success: function(data){
$("#status_div").html('The Garage Door Status is: ' + data);
}
})
}, 5000);
});
</script>
</head>
<body>
<div id="status_div"></div>
</body>
</html>
If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.
Create a page and named it status.php
status.php include these code:
$status = shell_exec('python /path/to/garage_door/myq-garage.py status');
echo $status;
Make another page index.php and include-
<div id="status_div">
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
url: "status.php",
dataType: "html",
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
Hope this will help you
If you are using ajax, you can make your life very easy:
function_status.php:
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
return $status; //avoid echo in such functions, try to not produce side effects
}
ajax_server.php:
<?php
require_once("function_status.php");
echo get_status();
index.php:
<?php
require_once("function_status.php");
?>
<html>
<body>
<div id="status">
<?php echo get_status(); ?>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript">
( //run function immediatly
function($){ //in this anonymous function, $ is always jQuery
function updateStatus(){
$.ajax({
url: "ajax_server.php"
type: "POST"
dataType: "json"
data: ({status: 1}),
success: function(data){
$("#status").html(data);
}
});
}
//first call it onload
$(function(e){
updateStatus();
}
//and then every 5 seconds
setInterval(updateStatus, 5000);
);
}
)//run function immediatly
(jQuery); //pass parameter jQuery to immediate execution of anonymous function
</script>
</body>
</html>
it is not a very clean way, and i used the <?php echo get_status(); ?> only, because your python script takes 4 seconds, so you would have no status for the first 4 seconds.
else you could change it to index.html and have a nicely seperated html and php, if you anyway want to populate the html with ajax.
if you really want to hack it into one file, you need an
if(isset($_POST['status'])){
echo get_status();
}else{
//output the html around the whole thing
}

How to use ajax to scrape one page at a time, return the next page link and go again

Question:
I have a php scraping function and code that all works well, however it times out because its trying to load 60 different pages...
I was thinking of using AJAX to load one page at a time in a loop. Since i'm very new to AJAX im having some trouble.
This is what I have so far, I can get it to loop through the links if I provide them, however I want it to scrape page 1, return the next page link and then scrape the next page on a continuous loop until there are no more pages. As it stands it goes into infinite loop mode...
Any ideas guys?
Here is my code which i took from a youtube video which was using an array (i am only passing through a string)
<?php
ini_set('display_errors',1);
//error_reporting(E_ALL);
set_time_limit(0);
require_once 'scrape_intrepid.php';
//posted to this page
if(isset($_POST['id'])) {
//get the id
$id = $_POST['id'];
//this returns the next page link successfully, i just cant get it back into the function
$ids = scrapeSite($id);
echo $ids;
echo "<br>";
$data = $id . " - DONE";
echo json_encode($data);
exit();
} else {
$ids = 'http://www.intrepidtravel.com/search/trip?page=1';
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
function update() {
ids = <?=json_encode($ids);?>;
if(ids){
var id = ids;
$.post("index.php",{id:id}).done(function(msg){
console.log(ids,msg);
update();
});
} else {
console.log("done");
$("#log").html("Completed!");
}
}
$("#go").click(function() {
$("#go").html("Loading...");
update();
});
});
</script>
</head>
<body>
<button id="go">Go button</button>
<div id="log">Results</div>
</body>
Ended up solving this in another way: The function I am calling to function.php runs the script and returns the next URL to scrape. which is the msg value, so the refresh is called again once this is validated. Just processed 60 pages each taking 38 seconds each :S
<script>
$(document).ready(function() {
refresh('http://www.intrepidtravel.com/search/trip?');
function refresh(url) {
$.ajax({
type: "GET",
url: "function.php",
data: 'url=' + url,
success: function(msg){
$('#result').append('--->Completed! <br>Next Page: is ' + msg);
console.log(msg);
if ($.trim(msg) == 'lastpage'){
$('#result').append('--->Last page - DONE!');
}
else {
refresh(msg);
}
}
}); // Ajax Call
} //refresh
}); //document.ready
</script>
And the function.php file:
require_once 'scrape_intrepid.php';
if ($_GET['url']){
$url = $_GET['url'];
if ($url=="lastpage"){
echo $url;
} else {
$nextlink = scrapeSite($url);
echo($nextlink);
}
}

How to check session before executing jquery preloader function?

I am trying to check session when my page loads , but when my page is loading it is calling preloader function first.
I want to check session before executing jquery preloader function.
Code for my preloader function:
$(window).bind("load", function () {
$('#work-in-progress').fadeOut(100);
});
I wants my preloader function to execute only if my session is false.
for example in my below code if spl is false then only I want to execute preloader function else I dont want to execute it.
Code for checking session:
var spl=('<?php echo $_SESSION['splash'] ?>');
if(!spl==true)
{
}
else
{
}
Within your script tag, if PHP var $_SESSION['splash'] is FALSE, then write the jQuery .bind function:
<?php if ( !$_SESSION['splash'] ) { ?>
$(window).bind("load", function () {
$('#work-in-progress').fadeOut(100);
});
<? } ?>
Why not something like:
<? if ($_SESSION['splash']): ?>
<script>
$(function() {
// do work
})
</script>
<? endif; ?>
???
also, if(!spl==true) is very confusing. You're expecting spl to be a Boolean, correct? Well, if spl = false, then your if statement will read if false is not false equal to true which is to say if (true == true)

Categories

Resources