3

I have an ajax system set up. When the MySQL query returns no data, I need it to pass an empty object back. I create a node called 'data' in the php script and even when the query returns no data I pass $data['success'] = 1.

The trick is I can't figure out how to check to see if the query was returned data or not.

I have tried...

// sub responseObj.data for responseObj.data[0] for the following if's
if(responseObj.data[0].length == -1)  

if(responseObj.data[0] == null)

if(responseObj == undefined)
//edit: added this...
if(!responseObj.data[0])

and I've really lost tack of any other various snippet's i've tried.

EDIT: adding xml generated that is passed to my script
XML - returning zero results

<response_myCallbackFunction>  
  <success>1</success>  
<response_myCallbackFunction>

XML - returning a populated query

<response_myCallbackFunction>  
  <data> 
  <random_data>this is data</random_data>  
  </data>  
  <success>1</success>  
<response_myCallbackFunction>

Is there a way to check to see if an object is empty in javascript?

-thanks

2

5 Answers 5

7

Obj.hasOwnProperty('blah') does not seem to work for checking to see if the property exists.

function isEmptyObj(obj){
  for(var i in obj){
    return false;
  }
  return true;
}

isEmptyObj({a:1}); //returns true

isEmptyObj({}); //returns false
Sign up to request clarification or add additional context in comments.

Comments

3

You could try

if( responseObj["data"] ) {
   // do stuff with data
}

or

if( responseObj.hasOwnProperty("data") && responseObj.data ) {
   // do stuff with data
}

4 Comments

nope... I thought responseObj.hasOwnProperty("data") would have done it... but no go... grr
ahh... I just read Obj.hasOwnProperty('property') cannot check for the existence of a property. ( javascript.about.com/od/reference/g/shasownproperty.htm )
not sure where you are looking... hasOwnProperty() can check for existence of a property (hence the name). Would suggest NOT reading about javascript on about.com :D
sure, Mozilla Developer Center has some great docs: developer.mozilla.org/En/…
1
if(typeof responseObj.data != 'undefined') {
   // code goes here
}

Comments

1

for ES5 you have getOwnPropertyNames :

var o = { a:1, b:2, c:3 };
Object.getOwnPropertyNames(o).length // 3

Comments

0

If responseObj is the XML Document object (from the xhr.responseXML property), then:

if (responseObj.getElementsByTagName("data").length > 0) {
    // do stuff...
}

If responseObj is a JavaScript object:

if (responseObj.data) {
    // do stuff...
}

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.