This object is empty, Javascript

I have ajax system installed. When a MySQL query does not return data, I need it to return an empty object. I create a node β€œdata” in a PHP script, and even when the request does not return data, I pass $ data ['success'] = 1.

The trick is that I can't figure out how to check if a request was returned by data or not.

I 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 really lost my binding on any other snippet I tried.

EDIT: adding generated xml which is passed to my script
XML - returning null results

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

XML - return a populated request

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

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

-Thanks

+4
source share
5 answers

Obj.hasOwnProperty('blah') doesn't seem to work to check if a property exists.

 function isEmptyObj(obj){ for(var i in obj){ return false; } return true; } isEmptyObj({a:1}); //returns true isEmptyObj({}); //returns false 
+7
source

You can try

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

or

 if( responseObj.hasOwnProperty("data") && responseObj.data ) { // do stuff with data } 
+3
source
 if(typeof responseObj.data != 'undefined') { // code goes here } 
+1
source

If responseObj is an 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... } 
0
source

for ES5 you have getOwnPropertyNames :

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

All Articles