My code works fine in this way. There are multiple div
s and $chat_id
is unique for each div
, so they look like:
<div id=chatbox_1>...
<div id=chatbox_2>...
...etc.
index.php:
<div id="chatbox_<?php echo $chat_id; ?>" >
<script type="text/javascript" >
$(document).ready(function(){
$('#chatbox_<?=$chat_id?>').load('chat.php?id=<?=$chat_id?>')
});
</script>
</div>
chat.php:
<?php
include 'db.php';
if (isset($_GET['id'])){
$c_id = $_GET['id'];
}
$query = "SELECT * FROM `chat` where `chat_id`='$c_id'";
$run = $con->query($query);
while($row = $run->fetch_array()){ ?>
<div id="chat_data">
<span style="color:brown;"><?php echo $row['msg']; ?></span>
</div>
<?php } ?>
The problem is when I am trying this ajax it is only working for one div
. Other div
s are not loading the chat.php
<div id="chatbox_<?php echo $chat_id; ?>" >
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chatbox_<?=$chat_id?>').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=<?=$chat_id?>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</div>
.load
is working perfectly but this ajax function is working for only one div
. The rest are empty. What should I change here, or should I use other method?
You should only have one general JavaScript function and it should not be inside the div
it's acting on. I am not very good at vanilla javascript, but it would be something like this:
<!-- You just load the id into the ajax function -->
<div id="chatbox_<?php echo $chat_id ?>" onload="setInterval(function(){ajax('<?php echo $chat_id ?>')},1000);"></div>
<!-- You only have one function and it is all javascript-based -->
<script type="text/javascript" >
function ajax(id)
{
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chatbox_'+id).innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id='+id,true);
req.send();
}
</script>
Your PHP should be adjusted to not have such an SQL and XSS vulnerability:
<?php
include('db.php');
# Check if the GET value is numeric (presuming it is supposed to be)
if(isset($_GET['id']) && is_numeric($_GET['id'])){
$c_id = $_GET['id'];
$query = "SELECT * FROM `chat` where `chat_id`='{$c_id}'";
$run = $con->query($query);
while($row = $run->fetch_array()){ ?>
<div id="chat_data">
<!-- You need to sanitize your output or you will have people taking advantage
of javascript hackery -->
<span style="color:brown;"><?php echo htmlspecialchars($row['msg'],ENT_QUOTES) ?></span>
</div>
<?php }
}