Forum Moderators: open

Message Too Old, No Replies

Error in Ajax Chatting Routine

         

calabar

3:10 pm on Apr 9, 2014 (gmt 0)

10+ Year Member



json_decode() expects parameter 1 to be a string ,array
given (CHATTING.PHP )


$(document).ready (function(){
var LLAST = 0;
function CHATTING(){
DATACOUNT = { "LLAST" : LLAST };
$.ajax({
type : "POST",
url : "http://localhost/AJAXPHP/JQUERY/CHATTING/CHATTING.PHP",
data : { "COUNTER" : DATACOUNT },
dataType : "json",
success : function(MESSAGES){
LLAST = LLAST + MESSAGES.Length;
var ULNODE = $("<UL>")
for ( COUNTER= 0;COUNTER < MESSAGES.Length; COUNTER++ ){
NAME = MESSAGES[COUNTER].NAME;
MESSAGE= MESSAGES[COUNTER].MESSAGE;
ULNODE.Append ( "<LI>" + NAME + ":" + MESSAGE + "</LI>" )
}
$("#CHATBOX").append ( ULNODE );
}
});


}
window.setInterval( CHATTING, 5000 );



});


##################################################################################
##################################################################################

CHATTING.PHP


<?php
header ('Content-Type : application/json');
$CON = mysql_connect( "localhost","root","");
mysql_select_db( "AJAXDBF", $CON );
$DATA = $_POST['COUNTER'];
$DATADECODE = json_decode( $DATA);
$LAST = $DATADECODE['LLAST'];
$SQLMESSAGE = " SELECT * FROM MESSAGES ";
$SQLMESSAGE.= " WHERE MESSAGEID > " . $LAST;
$FMESSAGE = mysql_query($SQLMESSAGE , $CON );
$MESSAGES = array();
while ( $ROW = mysql_fetch_array( $FMESSAGE)){
$ROW_ARRAY = array(
'NAME' => $ROW["NAME"],
'MESSAGE' => $ROW["MESSAGE"]
);
array_push( $MESSAGES, $ROW_ARRAY );

}
echo ( json_encode ( $MESSAGES ));
?>

Fotiman

3:23 pm on Apr 9, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




DATACOUNT = { "LLAST" : LLAST };

DATACOUNT is an object


data : { "COUNTER" : DATACOUNT },

COUNTER has an object value


$DATA = $_POST['COUNTER'];

$DATA gets the value of COUNTER (remember, that's an object, not a string)


$DATADECODE = json_decode( $DATA);

Can't decode because it's an object, not a string.

calabar

6:34 pm on Apr 9, 2014 (gmt 0)

10+ Year Member



WHAT IS THE CORRECT WAY TO SEND JSON USING AJAX.

Fotiman

9:38 pm on Apr 9, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm guessing you'd want to json_encode DATACOUNT, so that COUNTER will contain the JSON string instead of an object.

calabar

1:00 pm on Apr 10, 2014 (gmt 0)

10+ Year Member



what about JSON.stringify() .

Fotiman

1:12 pm on Apr 10, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, JSON.stringify would be the JavaScript version. So you could call that on DATACOUNT (sorry if my previous post caused any confusion... json_encode is a PHP method, so that didn't really make sense).