0

I have a script that basically check if there is a result from a query:

$.post('<?php echo site_url('xxx/yyy'); ?>',{data:no},function(result){
        if(!result){
            alert("No Data");
        }
        else{
            alert("Data retrieved");
        }
});

Why my IF alert Data retrieved when I get empty JSON array. I tried to do alert(result) with different data (the data which result is empty and result is true), but both data is alerting Data retrieved.

This is my model:

$this->db->select('*',FALSE);
    $this->db->from('t_penomoran tp');      
    $this->db->join('t_penomoran_detail t_pd', 'tp.nomor = t_pd.nomor');

    $this->db->where('tp.nomor',$nomor);

    $query = $this->db->get();
    return $query->result_array();

note:
For some reason when I do alert(result.length) with data that has no value, the result is 2. But when I do alert(result) with data that has no value the result is []

ashura91
  • 441
  • 4
  • 17
  • Empty JSON array [] in stringified form is still string, so maybe you need to parse the result to actual JSON first? – Daniel H.J. Oct 24 '17 at 04:51
  • @DanielH.J. _"[JSON (JavaScript Object Notation)](http://json.org) is a lightweight data-interchange format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others."_ - [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Oct 24 '17 at 04:57
  • 1
    Andreas, what I am saying is the Ajax result is an empty JSON array that is stringified, so [] is not the same as '[]'. '[]' is a string with length of 2. You need to parse the result first. – Daniel H.J. Oct 24 '17 at 05:07
  • @DanielH.J. If the server doesn't send `application/json` as the content-type you're right. Otherwise jQuery will automatically parse the response (https://jsfiddle.net/Lpt9n8q3/). – Andreas Oct 24 '17 at 10:48

3 Answers3

1

Empty array is a truthy value, meaning in your if statement, it will evaluate to true and that is why you see the alert(). To fix it, use the length property:

if(!result.length) alert('no data')
JohanP
  • 5,252
  • 2
  • 24
  • 34
  • still no luck. For some reason when I do `alert(result.length)` with data that has no value, the result is 2. But when I do `alert(result)` with data that has no value the result is `[]` – ashura91 Oct 24 '17 at 04:54
  • That correlates to result being a string of length 2, namely`”[]”` – James Oct 24 '17 at 05:22
0

You can check like this

 if(jQuery.isEmptyObject(result))
{
        alert('no data')
}
Jinesh
  • 1,554
  • 10
  • 15
0

First of all parse your result like this

var res = result.responseJSON;

Then alert what you get if empty then it will be null. so you can filter that out

Asmarah
  • 134
  • 8