Refresh contents of multiple divs on same page - javascript

I am trying to refresh/update the contents of multiple divs on the same page. I have a code I have been working with which works great for a single div but, I need to be able to refresh/update the content of multiple divs. The data is coming from a database. Here is an example of how that works.
data.php
<?php
include('dbconn.php');
$sql = "SELECT gpsStatus FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$gpsStatus[$i] = $row["gpsStatus"];
$i++;
}
}
$sql = "SELECT DisplayName FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$DisplayName[$i] = $row["DisplayName"];
$i++;
}
}
$sql = "SELECT ChaserLocation FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$chaserLocation[$i] = $row["ChaserLocation"];
$i++;
}
}
$sql = "SELECT StreamStatus FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$status[$i] = $row["StreamStatus"];
$i++;
}
}
$sql = "SELECT TimeStamp FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$timeStamp[$i] = $row["TimeStamp"];
$i++;
}
}
$conn->close();
<div class="left"><h3 class="panel-title"><?php if ($gpsStatus[1] == 'true' ) { echo "<i class='small material-icons' style='color:#00FF00; font-size:12px;' title='GPS Location Active'>gps_fixed</i>"; } else { echo "<i class='small material-icons' style='color:#FF0000; font-size:12px;' title='GPS Location Offline'>gps_fixed</i>"; } echo " $DisplayName[1]"; if ($gpsStatus[1] == 'true' ) echo " - $chaserLocation[1]"; ?></h3></div> <div class="right"><h3 class="panel-title"><?php if ($status[1] == 'true' ) { echo "<span class='label label-success' style='vertical-align:-40px;'><i class='fa fa-video-camera'></i> LIVE</span>"; } else { echo "<span class='label label-important'><i class='material-icons' style='vertical-align:-4px; font-size:14px;'>videocam_off</i> OFFLINE</span>"; } ?></h3></div><div style="clear:both;"></div>
Then I have a js file called update.js which looks like this that calls the above file...
$(document).ready( function(){
$('#chaser1').load('inc/data.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#chaser1').load('inc/data.php');
refresh();
}, 2000);
}
Then on my HTML page I call like so which refreshes the div...
<div class="col-md-3"> <div class="panel panel-primary">
<div class="panel-heading">
<div id="chaser1"></div>
</div>
This works great for a single div when the data in the DB updates the div updates but, I am unable to use this to update multiple divs. I have tried adding multiple calls to different files for each file and change the ID but then it only updates the last div. Is there a simplified way to update/refresh the data in multiple divs on the same page with the data from the database. This would work if I loaded all my HTML into the data.php but, the problem then arises that the panel body of the div contains a video player so it refreshes the video player too which is not want I want because this it will stop the player each time it refreshes and updates the divs.
-Thanks

It may not be the prettiest or most logical solution but, it functions as I am needing.
For my update.js I just added each ID like so and pointed each new ID to its own page like so.
$(document).ready( function(){
$('#chaser1').load('inc/chasers/ncopeland.php');
$('#chaser2').load('inc/chasers/ksaunders.php');
$('#chaser3').load('inc/chasers/rcontreras.php');
$('#chaser4').load('inc/chasers/nbusby.php');
$('#chaser5').load('inc/chasers/gyates.php');
$('#chaser6').load('inc/chasers/jcollum.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#chaser1').load('inc/chasers/ncopeland.php');
$('#chaser2').load('inc/chasers/ksaunders.php');
$('#chaser3').load('inc/chasers/rcontreras.php');
$('#chaser4').load('inc/chasers/nbusby.php');
$('#chaser5').load('inc/chasers/gyates.php');
$('#chaser6').load('inc/chasers/jcollum.php');
refresh();
}, 2000);
}
Then on the page for each div included the ID like so with the ID corresponding to the data which it is looking for and include all the markup and php on that page it is calling.
<div id="chaser1" class="panel-heading">
</div>
It may not be the most logical but, it appears to be working now.

Related

how to call ajax pagination function

I've succeeded display the data what I want based on the select box, but why is my pagination not working?
The index.php display with pagination not working
this is my ajax script to load data and pagination function
<div class="col-md-12">
<div class="table-responsive" id="show-level"></div>
</div>
</div>
</body>
</html>
<!---jQuery ajax load rcords using select box --->
<script type="text/javascript">
$(document).ready(function(){
load_data();
function load_data(page){
$(".level").on("change", function(){
var levelname = $(this).val();
if (levelname !== "") {
$.ajax({
url : "display.php",
type:"POST",
cache:false,
data:{levelname:levelname, page:page},
success:function(data){
$("#show-level").html(data);
}
});
}else{
$("#show-level").html(" ");
}
});
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and then this is my display.php where the pagination function is set
$output .= "</table>";
$page_query = "SELECT * FROM list WHERE level = 'sulit'";
$page_result = mysqli_query($con, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
}else{
echo "No records found";
}
?>
If $records_per_page is 10, and the number of total records is 100, the below will always give you the first 10 items.
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++) {
...
You should look at limiting the number of results and offsetting them in your SQL instead. For instance, you can limit your number of rows to 10, and then offset the results by the page number you are currently on (*10).
Here is what the statement would look like for page 2:
SELECT * FROM list WHERE level = 'sulit' LIMIT 10 OFFSET 10
So your code could look something like (I haven't tested this - but I think it should be about right):
$offset = $current_page * $records_per_page;
$page_query = "SELECT * FROM list WHERE level = 'sulit' LIMIT ? OFFSET ?";
$page_result = mysqli_prepare($con, $page_query);
mysqli_stmt_bind_param($page_result, 'ii', $records_per_page, $offset);
mysqli_stmt_execute($page_query);

unable to display images in a list after uploading using the user id

im trying to display images in a list after uploading, i want php to fetch the images using the 'user_id' from the database.
here's my php code
<div class="container-two">
<?php
$image = "";
$caption = "";
if ("POST" == $_SERVER['REQUEST_METHOD']){
$caption = $_POST['Caption'];
$con = mysqli_connect("localhost","root","Y1qSYlz1iTNBMCfY","schedios");
$query = "SELECT Img_dir FROM images WHERE user_id = '".$_SESSION['user_id']."' ";
$result = mysqli_query($con,$query);
$row = $result->mysqli_fetch_assoc();
$image = $row['Img_dir'];
}
?>
<div>
<?php
$array = array();
while ($row = mysqli_fetch_assoc($query) ) {
$array['user_id'] = $row['user_id'];
echo "<ul><li ><img src='$image' ></li></ul>";}
?>
</div>
i have a table of designers, so this is the dashboard, where the user can upload images and display , thanks in advance to help.
Why are you trying to fetch $query ?
$row = mysqli_fetch_assoc($query)
You should to do the same with $result if i'm getting you right
while ($row = mysqli_fetch_assoc($query) ) {
$image = $row['Img_dir']; // maybe add $row['Img_name'] if exist in your database
// $array['user_id'] = $row['user_id'];// you already know userid from $_SESSION, right ?
echo "<ul><li ><img src='$image' ></li></ul>";}
It seems that, you are trying to echo image dir in li only, so try to save full image path in database while uploading, let me give you, sample code to give an idea.
Receive image uploaded by user from form:
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO images (user_id,image)
VALUES
('".$_SESSION['user_id']."','$image')";
// execute query
mysqli_query($con, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images WHERE user_id =
'".$_SESSION['user_id']."' ");
?>
2.Display images back to user on unordered list:
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<ul><li>img src='images/".$row['image']."' /><li></ul>";
echo "</div>";
}
?>

ajax not work and not show php data

when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}

HTML, AJAX, PHP - Send a html input array through ajax to a php page

I have seen many similar questions however I have tried them and none of them worked.
I have a form in which the user can enter an unspecified amount of inputs. These inputs are selects and the user can add them when required. I am using ajax to add in more selects as required.
I am then trying to post this array to a php page using ajax, eventually to insert into a database
This is my html:
<strong>Allergens:</strong><br><div id="allergens">
<select name="allId[]" id="allId">
<option value="">No allergens</option>
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="addAllergen()">+</button><br></div><br>
Here is what I insert to add in more selects:
<div id="newSelect">
<select name="allId[]" id="allId">
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="removeNew()">-</button><br></div>
This is my ajax:
function addIng() {
if (confirm("Are you sure you want to submit?")) {
var toPost ={};
$form = $("#ingForm");
toPost.allId = [];
var allId = document.querySelectorAll("#ingForm input[name='allId[]']");
for (i = 0; i < allId.length; i++) {
toPost.allId.push(allId[i].value);
}
$.ajax({
type: "POST",
url: "../PHP/addIngredient.php",
data: toPost,
success: function(data) {
$("#addIngResult").html(data);
}
});
}
}
And then how can I set up my php so I can just call $_POST["allId"] and put it into an array?
On addIngredient.php page you will get the post value in $_POST['toPost'] variable as this is what writing in ajax

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

Categories

Resources