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.
Related
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();
}
?>
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
}
this is my ajax code to retrieve all data from a php file:
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "read.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
And this is part of my php file witch retrieves data from database and stores it into variables :
<?php
while($row = mysqli_fetch_assoc($result)){
$user_id = $row["user_id"]
$user_name = $row["user_name"]
$user_text = $row["user_text"]
}
?>
If I echo the above variables then they will be shown in my html page whitch contains ajax codes but I want to get each variable with ajax and do some operations on them and then show them in my html page
There is Simple html dom in php to get one page's html elements is there anything like php simple html dom for ajax? if not then how is it possible to do the things I said?
I'll be appreciate that if someone can help me with this:)
Server side
$array = array();
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
array_push(//what you need);
}
echo json_encode($array);
And on the client side
success: function(response){
data = $.parseJSON(JSON.stringify(returnedData));
}
Note that JSON.stringify is not needed however I like it
data is now an object and you can access its properties with data.propertyname
You have to return a JSON object with the variables. Make an array outside the while loop, and then on each while loop do array_push to the main array. After the loop echo the array through json_encode and then decode it on the ajax end.
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
I have web ecommerce, and it use an API from delivery agent website rajaongkir.com,
I want to use the price of delivery agent to be a variable in my database.
Her is file order.php
<script type="text/javascript" src="js/script.js"></script>
<form action="input.php?input=inputform" method="post">
<table class="zebra-table">
<thead>
<tr>
<th>Kurir</th>
<th>Servis</th>
<th>Deskripsi Servis</th>
<th>Lama Kirim (hari)</th>
<th>Total Biaya (Rp)</th>
<th>Opsi</th>
</tr>
</thead>
<tbody id="resultsbox"></tbody>
</table>
script.js
function cekHarga(){
//var origin = $('#oricity').val();
var origin = 35;
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
$.ajax({
url:'process.php?act=cost',
data:{origin:origin,destination:destination,weight:weight,courier:courier},
success:function(response){
$('#resultsbox').html(response);
},
error:function(){
$('#resultsbox').html('ERROR');
}
});
}
process.php
if(isset($_GET['act'])):
switch ($_GET['act']) {
$cost = $IdmoreRO->hitungOngkir($origin,$destination,$weight,$courier);
//parse json
$costarray = json_decode($cost);
$results = $costarray->rajaongkir->results;
if(!empty($results)):
foreach($results as $r):
foreach($r->costs as $rc):
foreach($rc->cost as $rcc):
echo "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$bayarr=$rcc->value;
endforeach;
endforeach;
endforeach;
endif;
}
endif;
I can access variable $bayarr at form in order.php.
How can I send variable $bayarr at process.php to order.php ?
use json to send more than 1 value from ajax call.
$arr['html'] = "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$arr['price'] = $bayarr=$rcc->value;
echo json_encode($arr);
In ajax success,
success: function(response){
var content = JSON.parse(response);
$('#resultsbox').html(response.html);
alert(response.price);// will have your price here.
}
If you want to get some specific value with the same request which gives you HTML you can add the param inside some of the HTML tags at your response and after that to parse it..
Something as:
foreach($rc->cost as $rcc):
echo "<tr data-bayarr=\"{$rcc->value}\"><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
endforeach;
After that just proceed it at your ajax succes as:
success:function(response){
$('#resultsbox').html(response);
/* Because its in a foreach there will be multiple bayarrs .. */
$('#resultsbox').find('[data-bayarr]').each(function( i ) {
alert($(this).data('bayarr'));
});
},
The other way is to convert the response into json array where you have both HTML and bayarr values..
You can encode your entire $results array, which you're looping, if you had to:
<input type="hidden" id="data_clustor" name="data_clustor"
value="<?php echo base64_encode(json_encode($results)); ?>">
Then just reference $('#data_clustor').val(); and pass it to your next PHP page where you'd simply do:
$results=json_decode(base64_decode($_POST['data_clustor']));
and loop it all over again. Or pass along only the data you're interested in rather than the whole entire massive array.
Without seeing your code which calls cekHarga() or the elements you're referencing with:
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
It becomes a bit difficult to see what you're trying to do, since it's unclear where you're pulling these fields with these ids from if none of the code you've showed us contains it.
Alternatively, just use PHP sessions, and keep the information loaded on the server for the specific user in $_SESSION. Write to it whatever you want to remember, then read from it when you need it on the other page.