Passing PHP variable via AJAX to PHP variable in another DIV - javascript

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
}

Related

Calling a PHP function using a radio button

I'm trying to call a PHP function via radio button onclick event, but it isn't working. I'm trying to use Ajax method to call the function, code as follows:
test0.php (php file with radio buttons):
<?php
include "test1.php";
echo '<input type="radio" id="1" name="rere" value="qwqw" checked onclick="testFunc();"><label for="1">radio 1</label>';
echo '<input type="radio" id="1" name="rere" value="qwqw" onclick="testFunc();"><label for="1">radio 2</label>';
echo '<div><p id="res">sdfdsfsdfsd</p></div>';
echo condCheckedUpd();
?>
<script>
function testFunc() {
$.ajax({
url: 'test1.php',
success: function(data) {
//alert(data);
}
});
}
</script>
test1.php (contains function to call)
<?php
function condCheckedUpd() {
echo "works";
}
?>
Think of your ajax call as if you're loading up a new tab in your browser. So, when you click the radio button, your call from test0.php is retrieving whatever gets responded to by test1.php, completely in isolation.
So, no need to include test1.php in your existing file- you're calling it separately! Your solution might be as simple as editing test1.php to execute the function when called, like so:
test0.php
<?php
//include "test1.php"; // no need to include this file here
echo '<input type="radio" id="1" name="rere" value="qwqw" checked onclick="testFunc();"><label for="1">radio 1</label>';
echo '<input type="radio" id="1" name="rere" value="qwqw" onclick="testFunc();"><label for="1">radio 2</label>';
echo '<div><p id="res">sdfdsfsdfsd</p></div>';
//echo condCheckedUpd(); //also no need for this function call here
?>
<script>
function testFunc() {
$.ajax(
{
url: 'test1.php',
success: function(data)
{
//alert(data);
}
});
}
</script>
test1.php
<?php
function condCheckedUpd() {
echo "works";
}
condCheckedUpd();
?>
You also asked about passing parameters along with your request, for that there's the data setting that you can include. For example, replace your javascript in test0.php above with something like:
<script>
//...^ all your existing php/html is still above
function testFunc() {
$.ajax({
url: "test0.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
Then, in test1.php, you can get your above parameters using the $_REQUEST global variable, and pass them into your function:
<?php
$getName = $_REQUEST['name'];
$getLocation = $_REQUEST['location'];
function condCheckedUpd($getName, $getLocation) {
echo "works for ".$getName." in ".$getLocation;
}
condCheckedUpd();
?>
For your purposes, I expect you probably want to get the value of your radio buttons. For that, you might look into html/javascript's dataset attribute as an easy way to pass these along (Examples and docs here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset).
Warning! If you're accepting values this way, be careful that what comes through in your $_REQUEST variables is what you expect, and be very careful if you end up displaying these back to the screen– lots of security concerns here. A few clues: How can I sanitize user input with PHP?
You can't call a function in your php file directly from the client. You can, however, pass data back which lets you determine which function to call.
For example, you could send back a query string test1.php?functionName=condCheckedUpd, and then in your test1.php file, you can check for it:
<?php
function condCheckedUpd() {
echo "works";
}
if ($_GET['functionName'] == 'condCheckedUpd') {
condCheckedUpd();
}
?>

Dynamic Array in HTML Datalist

I want to dynamically refresh the php code in this datalist, without reloading the whole page.
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr>
<td>Lecture auswählen: </td>
<td><input list="files" name="unterlage"></td>
</tr>
<datalist id="files">
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
</datalist>
I hope you can help me out.
You can write your html form in a "index.html" file. And uses javascript intervals request the data which provide by PHP in data.php. The pseudo-code will be something like this:
// index.html
<html>
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr><td>Lecture auswählen: </td><td><input list="files" name="unterlage"></td></tr>
<datalist id="files">
</datalist>
</form>
<script>
window.setInterval(function(){
function request_data(){
$.ajax({
url: 'data.php',
method: "post",
success: function (data) {
// Do something here
$("#files").html(data);
}
})
}
},2000); // 2 secends request a time
</scirpt
</html>
// data.php
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
return json_encode($files);
?>
Not entirely sure what your end goal is.
But one course of action is to set up an AJAX GET method that calls that PHP snippet in it's own file. Grab all the returning data and insert it into the page using JS.
Start learning JS because that's the only way you're going to be able to pull off dynamic content without page reloads.
To fetch the data using AJAX, use something similar:
<script>
$(document).ready(function(){
$.ajax({
url: 'URL_TO_PHP_FILE/scanFiles.php',
dataType: 'text',
success: function(data)
{
$("#files").html(data);
}
});
});
</script>
Now move your PHP snippet to it's own file simply as such:
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
Provided your only echos are what you would like to receive in your AJAX call, you should be good.
Also make sure you have the jQuery library linked to your page so that you can use AJAX. Take a look into jQuery a bit more. It'll make your life a lot easier.
You will also want a method to execute your JS code either every few seconds or a trigger based on previous user interaction.

Ajax doesn't show PHP data

I'm in a little trouble here. I'm trying to use ajax to get data from PHP server, that it gets from Mysql database; and then display into a specific html tag place. But, for some reason, nothing is showed off to html. I tested the PHP page and it works correctly. The point is, when ajax should get the data and display, it seems that there's nothing at database.
This is my html target :
<div class="container">
<table>
<thead>
<tr>
<th>Título</th>
<th>Curiosidade</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
This is my Ajax Script:
function readData() {
$.ajax({
type: "POST",
dataType: "html",
url: 'http://localhost/Gravidapp/php/read.php',
success: function(data){
$('tbody').html(data);
},
error: function(xhr,desc,err){
ajax.error(xhr);
ajax.error(desc, err);
}
});
};
This is my PHP file:
<?php
require("bdconn.php");
$pdo = new db();
$pdo->mysql->beginTransaction();
$rs = $pdo->mysql->query("select * from timeline");
$rs->execute();
while($row = $rs->fetch()){
?>
<tr>
<td><?php echo $row['titulocuriosidade']?></td>
<td><?php echo $row['curiosidade']?></td>
</tr>
<?php
}
?>
Any suggests?
Thanks in advance
If the php response doesn't have the data type on headers ajax response could send an error.
Try setting dataType="text html" on your ajax request this will try to convert the response from text to html
also try to print errors on console to show whats is going wrong.
error: function(xhr,desc,err){
console.log(desc);
}
see dataType on: JQuery ajax
What's happening is: when you make an ajax call you must have a return of some data in the php called. When you need to include html you can call a method that return to you a template already ready to be included in the current html page. You can have for example an index.html that will be included when you load your page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="data-ajax"></div>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="js/timeline.js"></script>
</body>
</html>
In you js timeline.js you will include in the current html page what has returned in the data of the ajax:
$.ajax({
type: "GET",
dataType: "html",
url: 'timeline.php',
success: function (data) {
$('#data-ajax').html(data);
}
});
You will have also your php returning the html to be used in the ajax:
<?php
getTimelineData();
function getTimelineData() {
//here you retrieve data from database
$results = array(0 => 'first-result', 2 => 'second-result', 3 => 'third-result');
include_once 'timeline-data.php';
}
And finally your timeline-data.php file:
Here is your data!
<?php foreach($results as $result) { ?>
<?= $result ?>
<?php } ?>

How to put the ajax response/result into variable php

Can I put the ajax response into variable? So that I can echo the variable into php?
ajax.php
<script>
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#random_no_container").html(result);//the result was displayed on this div
}
});
}
</script>
On my sample code above, i call the query result from test.php and the result was displayed on the div but i want to put that on the variable and echo the variable. something like the code below
<?php echo $variable;?>
Can this possible? please help me. Thank you so much.
You can't PHP is executed on server and Ajax from the client so you cannot assign PHP variable an ajax response.
Once a PHP is rendered on the client side it is just HTML no PHP code.
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}
As #dev answered , you need to execute server and client code differently ! I answered here for your need variable only .But in developing website, should not use javascript in php tag <?php ?>
ajax.php
<div id="random_no_container">
<?php
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
echo $variable;
} else {
echo "<script>sessionStorage.setItem('stopped',0);</script>";
}
?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
random_no();
}
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
sessionStorage.setItem("stopped",1);
//$("#random_no_container").html(result);//the result was displayed on this div
location.href = "ajax.php?variable="+result;
}
});
}
</script>

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

Categories

Resources