0

This is my ajax code, I need to check whether json data has an array or not? How can I? I have tried this but yet it shows me wrong output.

$.ajax({
        url: url,
        type: 'POST',
        data: {'data': data},
        dataType: "json",
        success: function (data) {
          if(data)
          {
            console.log('data is there');
          }
          else
          {
            console.log('data is not there'); 
          }

This is response I am giving in return to ajax.

<?php
$json_data_array = '[]';
return $json_data_array;
?>

How can I check?

1
  • JSON.parse(data).length Commented Nov 9, 2017 at 7:34

6 Answers 6

2

You need to check it's length. Array in condition if(array) is true when it has no items.

if([]) {
    console.log('True');
}

Check the length property

if([].length) {
   console.log('True');
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks which will be good options length or normal [] this for checking?
Depends on your logic. If empty array is ok (considering to be true) for you, use the first, if not - the second
1

In javascript you can check the length

  var size= myarray.length;
    if(size>=1) 
    {
       alert("not empty");
    }
    else
    {
        alert("empty");
    }

In php you can check with the following method

if(!empty($myarray))
{
    echo "Not Empty";
}
else
{
    echo "Empty";
}

Comments

1

First you need to json encode your return value from php like this

<?php
$json_data_array = '[]';
return json_encode($json_data_array);
?>

Then you have to check the length of returned array at javascript side like this

if(data.length > 0){
  console.log('data is there');
}else{
  console.log('data is not there'); 
}

Comments

1

You can check by using below method:

if( Object.prototype.toString.call( your_variable ) === '[object Array]' ) {
    alert( 'Array' );
}else{
    alert('Not Array');
}

Comments

0

use and echo json_encode($json_data_array);

build a normal array and then convert it to json it will be easier

<?php
$json_data_array = array();
echo json_encode($json_data_array);
?>

in your jquery use

if($.isEmptyObject(data))

Comments

-1

In javascript empty array ([]) return true. You should check array.length

Comments

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.