Reputation: 47985
I have this PHP function :
if(($_POST['id']=="pm_read") && (isset($_POST['pm_id'])) && (ctype_digit($_POST['pm_id'])) && (isset($_SESSION['nickname']))) {
$update=mysql_query("UPDATE pm SET readed='1' WHERE id='".$_POST['pm_id']."' AND receiver='".$_SESSION['nickname']."'",$mydb);
$query=mysql_query("SELECT COUNT(id) FROM pm WHERE receiver='".$_SESSION['nickname']."' AND readed='0' AND receiver_delete='0' ORDER by date DESC",$mydb);
$arrayPm[0]=mysql_result($query,0,'COUNT(id)');
$query=mysql_query("SELECT message FROM pm WHERE id='".$_POST['pm_id']."' AND receiver='".$_SESSION['nickname']."'",$mydb);
$arrayPm[1]=mysql_result($query,0,'message');
echo json_encode($arrayPm);
}
On client side, I get this array trought a jQuery function :
$.ajax({
type: 'POST',
cache: false,
url: 'pm/pm_ajax.php',
data: 'pm_id='+$(this).attr('id')+'&id=pm_read',
success: function(data) {
... here I'll print somethings...
}
});
Unfortunatly, if I print data
I get (for example) the string ["2", "message"].
So, if I try to do alert(data[0]) I'll see only [.
How can I access to this array printing the correct result? I mean :
data[0] must print 2 and data[1] must print message...
Upvotes: 0
Views: 278
Reputation: 6216
Never insert unfiltered $_POST superglobal into mysql_queries. That's a security flaw.
Obviously data is being returned as a string, so data[0] is the first character. Instead you want JSON. So make sure you use header() in PHP, to set content-type: application/json
So give this a try before you echo your output:
header('content-type: application/json');
Also make sure your jquery request has
dataType: 'json',
Upvotes: 3
Reputation: 18139
try adding
dataType:'json'
to your options in the ajax call.
Upvotes: 3