Reputation: 97
Afternoon
My php and Ajax is now almost complete, but I'm stuck on one thing I'm getting the data sent back through to the ajax but its only showing [object Object] in the div I've specified and I'm wanting the number of results sent back to be in there.
<? $call="SELECT * FROM notifications WHERE notification_targetuser='$user1_id' ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
$num=mysqli_num_rows($chant);
while($notification_id=mysqli_fetch_array($chant))
{
?>
<script type="text/javascript">
setInterval(function(){
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(response){
$("#mes").prepend(response);
}
});
},20000);
</script>
<? }?>
Vuewajax.php
<?php
include"database.php";
if(isset($_GET['notification_id'])){
$id=$_GET['notification_id'];
$user1_id=$_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num>0){
echo '<span id="mes">'.$num.'</span>';
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
mysqli_free_result($com);
echo json_encode($json);
}
?>
My returned response in firebug
<span id="mes">1</span>{"notification_id":"3306"}
Upvotes: 1
Views: 86
Reputation: 52809
This answer can seems to be off-topic but the code you show us is not secure. He's prone to easy sql injection
eg :
$id = $_GET['notification_id'];
$com = mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");
Injecting "'; DELETE FROM users WHERE 1 or username = ''" in your notification_id parameter will delete all your users !
Use prepared statements, it's easy and far safer an XKCD ;-)
Upvotes: 1
Reputation: 20469
You are returning a json object, so you need to access the correct propery, in this case notification_id
. Its also good practice to set the correct content-type header:
//php set json header
header('Content-Type: application/json');
echo json_encode($json);
//js access property of returned object
$("#mes").prepend(response.notification_id);
EDIT as per comment - if you are sending json, only send json, not mixed in html:
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);
//js
$("#mes").prepend('<span id="mes">'+ response.num + '</span>');
Further EDIT You can check the value of num, and only prepend if its not 0. As 0 evaluates to false, the following will work
if(response.num){
$("#mes").prepend('<span id="mes">'+ response.num + '</span>');
}
Upvotes: 1