I am successfully returning JSON from a PHP script, but I am having trouble displaying the appropriate message if the JSON object is empty.
The message is being displayed in an HTML UL tag with an ID of #precommentsload.
So here is the jQuery sending and returning the data from the PHP script:
$.post("api/searchComments.php", {uid:uid}, function(data)
{
if(data == '[]') // here's where I'm checking if JSON object is empty
{
console.log('no data'); // console displays this message when empty
// here's where I'm trying to output a message
var obj = JSON.parse(data);
$('#precommentsload').empty();
var htmlToInsert = obj.map(function(item)
{
return '<li>There were no comments.</li>';
}).join('');
$('#precommentsload').html(htmlToInsert);
}
else
{
console.log(data); // when object returns data, I can see it here
var obj = JSON.parse(data)
$('#precommentsload').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><b>' + item.add_date + ' - ' + item.add_user + '</b>
<br />' + item.comment.replace(/\r\n/g, '<br />') + '</li>';
// no problem displaying comments when object is not empty
}).join('');
$('#precommentsload').html(htmlToInsert);
}
});
After the $.post, I tried this IF statement:
if(data == []) // without the single quotes
But I only returned [] to the console when object is empty.
The point is, when the object is not empty, I can display the message accordingly.
It's getting the 'There were no comments' to display when the object is empty.