showing a loading message before appending - javascript

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>

Related

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);
}
}

Reload function that make fancybox appear

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>

How to use PHP variable in an external Javascript

I am trying use an array created in PHP in my external javaScript. I have PHP code that puts images from the directory depending on the userid given via url, into an array and I want to be able to use this array in javaScript so that I can create a photo slideshow and have the images change depending on the userid. I think this is achievable as I have researched online, but somehow it just doesn't work for me. I am not sure what I am doing wrong.
In the head of my html, I have this code to add in my external javaScript and to declare the variable/array in Javascript. Not sure if it's right, I got it off here from one of the solutions:
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Here is my PHP code inside my basic HTML:
And here is my external JavaScript code:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/" + userid + "/" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
PHP:
Have your PHP define the variable(s) inside of a <script> tag like this...
<script>
var userid = "<?php echo json_encode($user_id); ?>";
var userphoto = "<?php echo json_encode(galleryarray); ?>";
</script>
Your following external javascript files will then be able to use the userid and userphoto variables, even though they weren't defined directly in the external file
In the below code userphoto & userid are now javascript variables.
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Php code will not be executed in external javascript file. so when below lines are executed
userid will be a string with "< ? php echo json_encode($user_id); ? > " as its value and similarly for userphoto.
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
Modify your basic HTML to
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = <?php echo json_encode(galleryarray); ?>; </script>
<script type="text/javascript">var userid = <?php echo json_encode($user_id); ?>;</script>
<script src="javascript.js"></script>
and you can use these variables in external javascript file provided it is loaded after these variables are assigned. So you need not assign these variables in external javascript again.
Simply rename your file named javascript.js to javascript.php and change your script tag to <script src="javascript.php"></script>
Update
You also can use .htaccess to keep your javascript.js as it is in the script tag by doing something like the following in your .htaccess file:
RewriteRule ^javascript\.js$ javascript.php
For more details about using .htaccess in such case, checkout the
following question's answer:
Parsing PNG as PHP via htaccess works only on local server but not on webserver

Sending data to the clicked url via AJAX/PHP

I can't seem to send data to the link that I click on. All I'm getting is an undefined index in my php file.
Click me
('a').click(function(){
href = "output.php";
$.post( 'output.php', { output: "hello"},
function( data ) {
window.location = href;
}
);
return false;
});
The ajax successfully sends, but the page redirected to the output.php page with errors saying the index "output" doesn't exist.
<?php
$content = $_POST['output'];
echo $content;
?>
Help anyone? This is so confusing.
It's because output.php is being loaded twice: once on your Ajax request, and once when you change window.location.
The second time, there's nothing in $_POST, because the browser isn't making a post request at that point.
ADDED FOR CLARITY:
If you use Firebug, and take out the window.location line, you should see the Ajax request go out and the response from the server.
Okay. I'm still not sure what you're trying to do, or how the code you posted relates to it. But if you want to send data to the server via Ajax, and then have the browser load output.php and display that data, you could do something like this:
In your PHP:
if(isset($_POST["output"])){
$output = $_POST["output"];
echo $output;
} elseif (isset($_GET["output"])){
$output = $_GET["output"];
echo $output;
}
In your success callback:
window.location = href + "?output="+data
try this :
Demo.php
<html>
<head>
<title>Demo</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(){
$.post( 'output.php', { output: "hello"},function( data ) {
$("div").append(data);
}
);
});
});
</script>
<body>
Click Me
<div></div>
</body>
</html>
output.php
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
exit;
?>

Categories

Resources