John Beasley John Beasley - 16 days ago 6
Javascript Question

Display appropriate message when JSON object is empty

Code World...

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.

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.

Please help and thank you in advance.

Answer

var obj = JSON.parse(data); is returning an empty array. When you try to do .map the callback function you provide is never executed because it only executes on items in the array.

Instead why don't you skip all of that and just do

var htmlToInsert = '<li>There were no comments.</li>'
$('#precommentsload').html(htmlToInsert);
Comments