Javascript code stops working after page Load More .load() - javascript

When data is fetched on auto Load More, another JavaScript (which is given below) stops working.
Even when it shows the 1st page default it works there but after scrolling down it does not work.
Updated with more explaination with index and getdata file. I'm fetching data like mentioned in the below codes.
index.php
<div>
<?php include('getdata.php'); ?>
</div>
<script>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()+1},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
</script>
getdata.php
<?php
include ('db.php');
$perPage = 10;
$sql = "select * from posts where status = 1";
$faq3x = $dba3->query($sql);
$allrowscount = mysqli_num_rows($faq3x);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start <= 0) $start = 0;
$sqlsC = "select * from posts where status = 1 ";
$query = $sql . " limit " . $start . "," . $perPage;
$faq3xsC = $dba3->query($query);
echo '<input type="text" class="pagenum" value="'.$page.'" />';
echo '<input type="text" class="total-page" value="'.$pages.'" />';
while ($faqC = $faq3xsC->fetch_assoc()) {
$id = $faqC['id'];
$ext = ".doc";
$name = $id.$ext;
$filepath = "blog/posts/";
$filename = $filepath.$name;
if(file_exists($filename)) {
if(($fhP = fopen($filename, 'r')) !== false ) {
$headersxP = fread($fhP, 999000);
$commentsPP = nl2br($headersxP);
$countxP = 0;
$fhxP = fopen($filename, 'r');
while(!feof($fhxP)){
$frxP = fread($fhxP, 999999);
$countxP += strlen($frxP);
}
fclose($fhxP);
?>
<?php echo substr($commentsPP, 0, 511); ?>
<span id="dots_<?php echo $idPost; ?>">...</span>
<span id="more_<?php echo $idPost; ?>" style="">
<?php echo substr($commentsPP, 512, 999999); ?>
</span>
<a onclick="myFunctionx_<?php echo $id; ?>()"
id="myBtn_<?php echo $id; ?>"> See More <i class="fa fa-long-arrow-right"></i></a>
<script>
function myFunctionx_<?php echo $id; ?>() {
var dots_<?php echo $id; ?> = document.getElementById("dots_<?php echo $id; ?>");
var moreText_<?php echo $id; ?> = document.getElementById("more_<?php echo $id; ?>");
var btnText_<?php echo $id; ?> = document.getElementById("myBtn_<?php echo $id; ?>");
if (dots_<?php echo $id; ?>.style.display === "none") {
dots_<?php echo $id; ?>.style.display = "inline";
btnText_<?php echo $id; ?>.innerHTML = " See more <i class='fa fa-long-arrow-right'></i>";
moreText_<?php echo $id; ?>.style.display = "none";
} else {
dots_<?php echo $id; ?>.style.display = "none";
btnText_<?php echo $id; ?>.innerHTML = " <i class='fa fa-long-arrow-left'></i> See less";
moreText_<?php echo $id; ?>.style.display = "inline";
}
}
</script>
<?php } ?>

Related

What should I put in my updating.php when I need to update users status if online or offline every 5 seconds?

Hi I've made a messaging feature,it displays the receivers of the message in an account, beside the receiver's name is a green or red dot, for online or offline, it is successful when I log in 2 accounts and messaged each other, when I open the first account, the other account is offline, when I open the second account, the other is online, what my problem is I want to update their status in every five seconds so that their dot will be accurate whenever they log out or log in. I have made a javascript and ajax below this page left-col.php and I've tried copying the whole code, putting it to updating.php but it did not work, what should be the appropriate data inorder to update user receiver status in every 5 seconds inside the updating.php? and also, does my the javascript and ajax needs a library to be included that's why it didn't work? Please help.
<?php
require('connection.php');
$user_name=$_SESSION['username'];
$user_id=$_SESSION['user_id'];
if(!isset($_SESSION['user_id'])){
header("LOCATION: index.php");
}else{
$advance_time=time()+15;
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q='SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="'.$_SESSION['username'].'" OR
`receiver_name`="'.$_SESSION['username'].'"
ORDER BY `date_time` DESC';
$e='SELECT * from messages';
$r=mysqli_query($con,$q);
if($r){
if(mysqli_num_rows($r)>0){
$counter=0;
$added_user=array();
while($row=mysqli_fetch_assoc($r)){
$sender_name=$row['sender_name'];
$receiver_name=$row['receiver_name'];
$timestamp=$row['date_time'];
if($_SESSION['username']==$sender_name){
//add the receiver_name but only once
//so to do that check the user in array
if(in_array($receiver_name,$added_user)){
//dont add receiver_name because
//he is already added
}else{
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo ''.$receiver_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user=array($counter=>$receiver_name);
//increment the counter
$counter++;
}
}elseif($_SESSION['username']==$receiver_name){
//add the sender_name but only once
//so to do that check the user in array
if(in_array($sender_name,$added_user)){
//dont add sender_name because
//he is already added
}else{
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo ''.$sender_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user=array($counter=>$sender_name);
//increment the counter
$counter++;
}
}
}
}
else{
//no message sent
echo 'no user';
}
}else{
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#content').html(response);
}
});
}
</script>
You need to handle the $_SESSION in all pages
Updating.php code:
<?php
require('connection.php');
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if(isset($_REQUEST['from_user'])){
$advance_time=time()+15;
$user_id = $_REQUEST['from_user'];
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
$html_left_div = '';
$html_left_div .='<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById(\'new-message\').style.display=\'block\'" class="white-back">
<p align="center">New Message </p>
</div>';
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
// echo $q;
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
$html_left_div .='<div class="grey-back first">
<img src="s.jpg" class="image"/>
' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$receiver_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
$html_left_div .='<div class="grey-back second">
<img src="s.jpg" class="image"/>
' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$sender_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
$html_left_div .='</div>';
echo $html_left_div;
Left-col.php code:
<?php
require 'connection.php';
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if (!isset($_SESSION['user_id'])) {
header("LOCATION: index.php");
} else {
$advance_time = time() + 15;
$query = mysqli_query($con, "SELECT * FROM status WHERE user_id='$user_id'");
if (mysqli_num_rows($query) > 0) {
mysqli_query($con, "UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
} else {
mysqli_query($con, "INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo '' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo '' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#left-col-container').html(response);
}
});
}
</script>

innerHtml on responding ajax method

I am using ajax for sending data to PHP script and set a query in my database. my codes :
HTML script :
<span id="btn_span_<?php echo $user_id ?>">
<?php if ($online == 1) { ?>
<button onclick="update_online(1,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-delete btn btn-status">is active</button>
<?php } elseif ($online == 0) { ?>
<button onclick="update_online(0,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-services btn btn-status">active
</button>
<?php } ?>
</span>
JAVASCRIPT script :
function update_online(status, id, span_id) {
var settings = {
"async": true,
"crossDomain": true,
"url": "script_edit_status.php?status=" + status + '&id=' + id + '&span_id=' + span_id,
"method": "GET"
};
$.ajax(settings).done(function (response) {
var obj = JSON.parse(response);
var btn = document.getElementById(span_id);
if (obj.status == "1") {
btn.innerHTML = "<button onclick='update_online(1,obj.id,obj.span_id)' class='btn-custom-services btn btn-status'>active</button>";
} else if (obj.status == "0") {
btn.innerHTML = "<button onclick='update_online(0,obj.id,obj.span_id)' class='btn-custom-delete btn btn-status'>is active</button>";
}
});
}
PHP script :
<?php
include_once "../db/connection.php";
$id = $_GET['id'];
$status = $_GET['status'];
$span_id = $_GET['span_id'];
try {
if ($status == 1) {
$sql_edit_status = "update api_user set online=0 where id='$id';";
} elseif ($status == 0) {
$sql_edit_status = "update api_user set online=1 where id='$id';";
}
$conn->query($sql_edit_status);
$status_arr = array(
"id" => $id,
"status" => $status,
"span_id" => $span_id
);
echo json_encode($status_arr);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
it is ok for the first action but when I want to click to button for second time consol shows following error :
Uncaught ReferenceError: obj is not defined
The error is for innerHTML that don't send correctly methods...
Can you help me?
btn.innerHTML = "<button onclick='update_online(0," + obj.id + "," + obj.span_id + ")' class='btn-custom-delete btn btn-status'>is active</button>";

JavaScript/AJAX prints weirdly

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

PHP/HTML button picture change and script call

I have a page with buttons that a user clicks on.
When the button gets clicked I need it to change the image and call a php script to save the change.
I somehow can't get the button to do both, it changes the pic but won't call the php.
CODE:
<?php
$db = new PDO('mysql:host=localhost;dbname=MySettings;charset=utf8mb4', 'TestUser', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$mytable = $_SESSION["SESS_myuserid"];
if($mytable == null)
{$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
$stmt = $db->prepare("SELECT * FROM ".$mytable);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn = null;
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo '}';
}
echo'</script>';
$myLeft=0;
$myTop=0;
$myRow=0;
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
$ThePic = "images/Boff.png";
}
else{
$ThePic = "images/Bon.png";
}
echo '<div>';
echo ' ';
echo '</div>';
$myTop=$myTop + 30;
$myRow=$myRow + 1;
if ($myRow == 12){
$myRow=0;
$myTop=0;
if ($myLeft == 0){
$myLeft = 292;
}
else {
$myLeft = 615;
}
}
}
}
catch(PDOException $e) {
$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>
Fixed :
Changed the script function. Added a hidden div to be called to load the php which outputs nothing so stays invisible.
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo' $("#HtmlConvo").load("Monitor.php?id='.$TheId.'&Table='.$mytable.'");';
echo '}';
}
echo'</script>';

use dynamic php variable in javascript

i have a image database and a search form , so i want to show the images in next page and i have to use javascript to show (openlayer library)
i wrote this code`
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$am=0 ;
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
$count = mysql_num_rows($result);
for ($i=1; $i<=$count; $i++)
{
$rows = mysql_fetch_array($result);
${'a'.$i}=$rows['xpos'];
${'b'.$i}=$rows['ypos'];
${'c'.$i}=$rows['width'];
${'d'.$i}=$rows['height'];
${'e'.$i}=$rows['xoffset'];
${'f'.$i}=$rows['yoffset'];
${'g'.$i}=$rows['rotation'];
${'h'.$i}=$rows['resolution'];
${'i'.$i}=$rows['name'];
${'j'.$i}=$rows['url'];
}
?>
and the javascript code:
var a1="<?php echo $a1?>";
var b1="<?php echo $b1?>";
var c1="<?php echo $c1?>";
var d1="<?php echo $d1?>";
var e1="<?php echo $e1?>";
var f1="<?php echo $f1?>";
var g1="<?php echo $g1?>";
var h1="<?php echo $h1?>";
var a2="<?php echo $a2?>";
var b2="<?php echo $b2?>";
var c2="<?php echo $c2?>";
var d2="<?php echo $d2?>";
var e2="<?php echo $e2?>";
var f2="<?php echo $f2?>";
var g2="<?php echo $g2?>";
var h2="<?php echo $h2?>";
var l1=340;
var l2=346;
if("<?php echo $count?>"==1){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
} else if("<?php echo $count?>"==2){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
anArray[anArray.length] = [ a2,b2, c2, d2, e2, f2, g2, h2,l2,"image/<?php echo $j2?>.jpg"];
} else if("<?php echo $count?>"==3){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
anArray[anArray.length] = [ a2,b2, c2, d2, e2, f2, g2, h2,l2,"image/<?php echo $j2?>.jpg"];
anArray[anArray.length] = [ a3,b3, c3, d3, e3, f3, g3, h3,l3,"image/<?php echo $j3?>.jpg"];
}
when in the database search i have two result this code work properly but when the result is more than two the code doesnt work, i know the problem is about my variable in javascript but i have no idea to fix it , can any one help me to solve it??
PHP :
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$ARR_DATA = array();
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
while($rows = mysql_fetch_array($result)
{
$arr_temp['a'] = $rows['xpos'];
$arr_temp['b'] = $rows['ypos'];
$arr_temp['c'] = $rows['width'];
$arr_temp['d'] = $rows['height'];
$arr_temp['e'] = $rows['xoffset'];
$arr_temp['f'] = $rows['yoffset'];
$arr_temp['g'] = $rows['rotation'];
$arr_temp['h'] = $rows['resolution'];
$arr_temp['i'] = $rows['name'];
$arr_temp['j'] = $rows['url'];
$ARR_DATA[] = $arr_temp;
}
$count = count($ARR_DATA);
?>
JS :
<script>
<?php
foreach($ARR_DATA as $key=>$arr_temp)
{
?>
var a = "<?php echo $arr_temp['a'];?>";
var b = "<?php echo $arr_temp['b'];?>";
var c = "<?php echo $arr_temp['c'];?>";
var d = "<?php echo $arr_temp['d'];?>";
var e = "<?php echo $arr_temp['e'];?>";
var f = "<?php echo $arr_temp['f'];?>";
var g = "<?php echo $arr_temp['g'];?>";
var h = "<?php echo $arr_temp['h'];?>";
var i = "<?php echo $arr_temp['i'];?>";
var j = "<?php echo $arr_temp['j'];?>";
var img = "image/"+j+".jpg";
anArray[<?php echo $key;?>] = [ a, b, c, d, e, f, g, h, i, j];
<?php
}
?>
</script>
try
in php code
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$am=0 ;
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
$count = mysql_num_rows($result);
$images = array();
for ($i=1; $i<=$count; $i++)
{
$rows = mysql_fetch_array($result);
$images[] = $rows;
}
?>
in js code
<?php
foreach ($images as $image){
?>
anArray[anArray.length] = [ "<?php echo $image['xpos'];?>","<?php echo $image['ypos'];?>", "<?php echo $image['width'];?>", "<?php echo $image['height'];?>", "<?php echo $image['xoffset'];?>", "<?php echo $image['yoffset'];?>", "<?php echo $image['rotation'];?>", "<?php echo $image['resolution'];?>","<?php echo $image['name'];?>","image/<?php echo $image['url']?>.jpg"];
<?php
}
?>
the safiest way to communicate between php and js is to use json in my opinion. additionnaly, I would suggest you to use pdo or mysqli instead of mysql for the communication with your database.

Categories