Getting correct value of num_rows back AJAX/JSON - php

I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));

You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.

Related

Select the last inserted row Every 1 second

I have 2 files:
1. chat.php: contain chat messages.
2. loadSingle.php: grab last new message every 1 second.
When I get the last message it was always return and get the last one. I want to get the last message without duplicate every time.
chat.php:
function loadlastmsg(){
var fromIdl = "<?php echo $chat_from_id;?>";
$.ajax({
type:'POST',
url:'loadSingle.php',
data:{fromIdl: fromIdl,},
cache: false,
beforeSend:function(data){
},
success: function(data)
{
$('#mainmsgs').append(data);
}
});
}
setInterval(function(){
loadlastmsg();
}, 1000);
</script>
Load Last Message
loadSingle.php:
<?php
if(isset($_POST["fromIdl"], $_POST["fromIdl"]))
{
$chat_from_ids = $_POST["fromIdl"];
require_once 'config/config.php';
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query("SELECT * FROM chat WHERE id = (SELECT MAX(id) FROM chat WHERE to_id=$userId AND from_id=$chat_from_ids OR to_id=$chat_from_ids AND from_id=$userId) ORDER BY chat.send_date DESC LIMIT 1");
while ($chinbxsx = mysqli_fetch_assoc($result)) {
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if($from_id != $userId){
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}else{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
// if($get_date > $get_date){
echo "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
// }
}
$conn->close();
}
?>
The mistake is: get the last message every 1 second. every time without stop it. I want to get the last message one time without loop the last message. thanks.
Using Ajax for chat will have poor performance always. You must consider using Web sockets.
See the below link for a sample
https://phppot.com/php/simple-php-chat-using-websocket/
I can't warranty this will be a fixed code, but it will give you the idea of how to discard a message on the client side if already received:
CLIENT SIDE:
<script>
/* Other code ... */
// Global variable for save the latest message ID.
var _latestMessageID = -1;
$(document).ready(function()
{
// Start getting messages...
setInterval(
function() {loadlastmsg();},
1000
);
});
function loadlastmsg()
{
var fromIdl = "<?php echo $chat_from_id;?>";
var formData = {fromIdl: fromIdl};
$.ajax({
type:'POST',
url:'loadSingle.php',
data: $.param(formData),
cache: false,
success: function(data)
{
if (data && data["ID"] > _latestMessageID)
{
$('#mainmsgs').append(data["message"]);
_latestMessageID = data["ID"];
}
}
});
}
</script>
SERVER SIDE:
<?php
require_once 'config/config.php';
if(isset($_POST["fromIdl"]) && $_POST["fromIdl"])
{
$chat_from_ids = $_POST["fromIdl"];
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query(
"SELECT *
FROM chat
WHERE id = (SELECT MAX(id)
FROM chat
WHERE (to_id=$userId AND from_id=$chat_from_ids)
OR (to_id=$chat_from_ids AND from_id=$userId))
ORDER BY chat.send_date DESC LIMIT 1"
);
// Since the query has LIMIT of 1 this should only loop one time.
while ($chinbxsx = mysqli_fetch_assoc($result))
{
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if ($from_id != $userId)
{
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}
else
{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
$msgID = $chinbxsx['id'];
}
$returnArray = array();
$returnArray["ID"] = $msgID;
$returnArray["message"] = "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
echo json_encode($result);
$conn->close();
}
?>

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

How should I execute my php code using AJAX?

I've written the conditions down in JavaScript and if it's a down arrow then I want to update the database whereas currently it's not falling into the javascript condition and updating the database at server level. Any help will be appreciated.
Code:
<script language="javascript">
$(document).ready(function() {
totalgames=<?= $totalgames ?>;
//scoress = 0;
previous_s=0;
for(xx=totalgames; xx>=1; xx--){
score_ele = 'scores'+xx;
tdid_ele = 'tdid'+xx;
var tdd = document.getElementById(tdid_ele);
var scoress = document.getElementById(score_ele);
if(previous_s == 0){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}else{
if(parseFloat(previous_s) > parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_up.png'/>";
}else if(parseFloat(previous_s) < parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_down.png'/>";
<?php
//Selecting from table teams
$sql_sel_amnt = "Select * from teams where t_name='".$t_name."'";
$result_sel = $db1->getResult($sql_sel_amnt);
$row_sel = mysql_fetch_assoc($result_sel);
//Selecting from table profitnloss
$sql_pnl = "Select * from profitnloss where t_name='".$t_name."' and username='".$abc."'";
$result_pnl = $db1->getResult($sql_pnl);
$row_pnl = mysql_fetch_assoc($result_pnl);
$transact_money = $row_pnl['pnl_amount'];
$pnl_results = $row_pnl['pnl'];
$profit = 0;
$loss = 0;
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='P'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$money_results_total = $profit - $loss;
$pnl_date = date("d-m-Y H:i:s");
$pnl_amount = $row_sel['c_amount'];//total amount lost
$t_amount = $money_results_total + $row_pnl['t_amount'] + $pnl_amount;
$noofplayers = mysql_num_rows($result_sel)-1;//total no of players
$company_share = 17;//charity percentage
$company_share_amnt = $company_share*$pnl_amount/100;
$pnl_amount_remaining = $pnl_amount - $company_share_amnt;
$charity = substr($row_sel['charity'], 0, 2);//charity percentage
$charity_amount = $charity*$pnl_amount_remaining/100;
$sharing_amount = $pnl_amount-$charity_amount-$company_share_amnt;
$pnl_profit = round($sharing_amount/$noofplayers, 2);
echo "noofplayers=> ".$noofplayers.", company_share=> ".$company_share.", company_share_amnt=> ".$company_share_amnt.", charity=> ".$charity."%, charity_amount=> ".$charity_amount.", sharing_amount=> ".$sharing_amount.", pnl_profit=> ".$pnl_profit;
$sql_updt_loss = "UPDATE profitnloss SET game_date = '".$serial_date."', pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_amount|'), pnl = CONCAT(pnl, 'Loss|'), t_amount='".$t_amount."' where username='".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_loss = $db1->getResult($sql_updt_loss);
$sql_updt_profit = "UPDATE profitnloss SET pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_profit|'), pnl = CONCAT(pnl, 'Profit|') where username not like'".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_profit = $db1->getResult($sql_updt_profit);
?>
}else if(parseFloat(previous_s) == parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}//end if
}//end if 0..
previous_s = document.getElementById(score_ele).value;
}//end for
})//emd document ready..
</script>
The way you should execute you PHP-code using ajax is by moving the server side code to a separate file which you call apon in the ajax-request, the url.
One example is using jQuery.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
This documentation is located here
You send the information needed to execute the PHP-code in the data. These are then accessed by $_POST or $_GET depending on which type you chose.
If you're not intending to use jQuery, you can look here: Getting Started with AJAX - Updating Form via PHP.
Here are some good practices using ajax

Passing data back from php to ajax

How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);

json_encode in php

i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"
{"valor":"20"},{"valor":"50"}
i need
{"valor1":"20"},{"valor2":"50"}
the script
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while($row = mysql_fetch_assoc($query)) {
$arr[] = $row;
}
echo json_encode($arr);
in ajax
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery.ajax({
url: "chart.php",
dataType: "json",
success: function(json){
var msg = "Nome: " + json.valor1+ "\n";
msg += "Sobrenome: " + json.valor2 + "\n";
alert(msg);
}
});
});
});
</script>
the problem is: I need to create a loop that create uniques names, as value1, value2, value3
like
$arr['valor1'] = "Evandro";
i tried a loop- for, but i get an error of memory
thanks
Try this:
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array("valor{$i}" => $row["valor"]);
++$i;
}
echo json_encode($arr);
Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:
$arr["valor{$i}"] = $row["valor"];
$index = 1;
while($row = mysql_fetch_assoc($query)) {
$key = 'valor'.index;
$arr[$key] = $row;
$index++;
}
Does that give you a memory error? It shouldn't.

Categories