tags:

views:

145

answers:

4

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 successful 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.

Is there a way to check to see if a data node is empty in javascript? Does this need to happen in the PHP side of things?

EDIT: adding xml generated that is passed to my script
XML - returning zero results (replaced <> with [] as SO doesn't process xml tags properly Edited to fix that - you need a blank line before the indented code block)

<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>

-thanks

+2  A: 

you could try

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

or

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

you can test this code here:

http://bit.ly/70sM7D

Jared
nope... I thought responseObj.hasOwnProperty("data") would have done it... but no go... grr
Derek Adair
ahh... I just read Obj.hasOwnProperty('property') cannot check for the existence of a property. ( http://javascript.about.com/od/reference/g/shasownproperty.htm )
Derek Adair
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
Jared
probably a good call... thanks
Derek Adair
could you link some valid docs on hasOwnProperty()?
Derek Adair
sure, Mozilla Developer Center has some great docs: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Global_Objects:Object:hasOwnProperty
Jared
+4  A: 

Here we go. 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
Derek Adair
A: 

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...
}
NickFitz
+1  A: 
if(typeof responseObj.data != 'undefined') {
   // code goes here
}
zincorp