I have this index.php file to show some stuff in tables from loop:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>
However, I wish to have auto refresh for those tables. So I have this new file data.php and a updated index.php:
data.php:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);
index.php:
<div id="show"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; </th></table>
<?php } ?>
This will refresh and print the output in the above <div>:
<div class="show"></div>
And it works great, but I don't really have any clue how to put that inside the loop for the tables, just as the first index.php file. Any suggestions of a direction to take in this matter?
You can use ajax to call data.php and return the response in json format for a better approach
Try:
js
function populate(){
var items= [];
$.ajax({
url: 'data.php',
type: 'GET',
dataType: 'json',
success: function(data){
//do something with data here
console.log(data);
//loop through data and push to array
$.each(data, function(i,v){
items.push('< th >'+v+'< /th >');
});
//join array and append to table
$('#sampleTable tbody').html(items.join(','));
},
error: function(err){
console.log(err.responseText);
}
});
}
//call populate every 10 secs (example only , you can change to how many seconds you like)
setTimeout(function(){
populate();
},10000);
data.php
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
In this line you forgot to close <?php ...
Possibly that's why foreach loop doesn't work correctly
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?></th></table>
<?php } ?>
Put these lines in data.php where print_r() is.
Related
It seems like when i echo out the result in php, it will loop through the database and display it in the "echo" below but if I try to display it using javascript, it does not even loop. what's the problem in the javascript?
<?php
while($row = $result->fetch()){
$id = $row['id'];
echo $id; //loops through and displays the all the id's in order in the database
?>
//this only displays the first id and doesn't loop even though it is in the php while loop
<script>
document.getElementById("test").innerHTML = "<?= $id ?>";
</script>
<span id="test"></span>
<?php
}
?>
please try with this
<?php
while($row = $result->fetch()){
$id = $row['id'];
echo $id; //loops through and displays the all the id's in order in the database
?>
//this only displays the first id and doesn't loop even though it is in the php while loop
<!-- change in id name -->
<span id="test_<?=$id?>"></span>
<script type="text/javascript">
//change here
document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>";
</script>
<?php
}
?>
What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id
Here, If I write name of textbox is id from an array, then how it would be use in session.?
Updated:
My code is:
foreach($abc as $row)
{
<input type="text" name="<?php echo $row['id']; ?>" class="txt" id=txt_"<?php echo $row['id']; ?>" onblur="doAjax(this)"/>
}
Javascript code:
$(document).on('blur','.txt',function(){
$.ajax({
type: "GET",
url: "view_orders_checked_array.php",
data: {task: 'alltxt'},
async: false
});
});
In view_orders_checked_array.php:
if($task == "alltxt")
{
$_SESSION["textareaID"] = [];
foreach($rows as $row)
{
$al[] = array_push($_SESSION["textareaIDs"], $row["id"]);
}
print_r($al);
}
So, how it would possible to store textbox value in session array.?
Start the session at the top of every page that you want to access the session:
<?php session_start();
Then to add data to the session array:
<?php $_SESSION["foo"] = $bar; ?>
So if your textarea ID is $row["id"], you can do:
<?php $_SESSION["textareaID"] = $row["id"]; ?>
then call it whenever you want by doing:
<?php echo $_SESSION["textareaID"]; ?>
Of course, you can name the session array variable anything you want.
Or in a foreach loop:
<?php
$_SESSION["textareaIDs"] = [];
foreach($rows as $row){
array_push($_SESSION["textareaIDs"], $row["id"]);
} ?>
As I wrote in the title I have this part of code in page page.php that is in a subfolder admin. So the path of page is ../admin/page.php:
<select name="my_select" id="my_select" onchange="function(this.value);">
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
}
?>
</select>
$var = $_POST['my_select'];
echo "I have selected $var";
I use a function that I have found on internet:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'page.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("my_select").innerHTML=response;
}
});
}
What I have to do to take value in $var? Because I need this value to build other things. Is it possible?
EDIT:
Probably I don't explain very well my problem. I don't have very good with ajax because I never use it. I have a deadline so I can't study it now.
Now I have this situation:
I have a select-form with an input submit. After click on the button I use $_POST['myoption'] and I get the value.
Then I do it:
if($var == 1)
//a query from database
else if($var == 2)
//another different query
else
//other but no query
This work correctely. I need to change it and use in the same page. How can I do the same?
You don't to do a POST to do this you can do it with jQuery.
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
?>
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
<span id="selected"></span>
<script>
$("#my_select").change(function() {
$("#selected").html($("#my_select option:selected").text());
});
</script>
This will give the select value to PHP:
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
if (isset($_POST['my_select'])) {
$var = $_POST['my_select'];
} else {
$var = '';
}
?>
<form id="my_form" action="" method="POST">
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
</form>
<span id="selected">I have selected <?php echo $var; ?></span>
<script>
$("#my_select").change(function() {
$('#my_form').submit();
});
</script>
I just need some ideas how i get the value from the dropdown
<select id="ins" name="instructor" required>
<?php
//dropdown instructor name
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from instructor";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value=".$row['insA_I'].">".$row['insname']."</option>";
}
?>
</select>
and put the value in this .php file in $_POST['instructor']
<?php
session_start();
require 'connection.php'; //connection
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$_SESSION['row'] = mysqli_fetch_array($result);
$data = $_SESSION['row']['course'];
echo $data;
?>
am still new in ajax
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: '',
datatype: 'json',
success: function(result){
alert(result);
}
});
});
});
i already searched this in internet but didn`t get my answer after some modifcation
just need idea, techniques .etc.
Try this ajax code
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: {instructor:$(this).val()},
success: function(result){
alert(result);
}
});
});
});
php code for query
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$fetch = mysqli_fetch_array($result);
$_SESSION['row']['course']=$fetch['course'];
$data = $_SESSION['row']['course'];
echo $data;
Since you're using jQuery, use jQuery:
data: { instructor: $('#ins').val() }
Also, please note that your SQL query is wide open to SQL injection. This is a good place to start reading about that.