1

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.

0

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

YES!!!! That was what I was looking for, and it worked. Thank you, good sir. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.