0

I have a JSON data that is returned by AJAX:

PHP file:

//SQL: fetch result if user exist
    $result = array("Name"=>$name, "ID"=>$id, "Age"=>$age, "School"=>$school, "Department"=>$dept);
    echo json_encode($result);
//else return error
    $error = 'No record for this user.';
    $result = array("Error"=>$error);
    echo json_encode($result);

jQuery AJAX:

//AJAX result
request.done(function( msg ):
//alert( msg ); working fine for users who exist and even those who doesn't exist.
var detail = jQuery.parseJSON( msg );
 if ( detail.Name.length > 0 ){
      $('.student').slideDown(300);
      $('.student').html(detail.Name);
      // this is working fine
    }
 if ( detail.Error.length > 0 ){
     $('.student').slideDown(300);
     $('.student').html(detail.Error); 
     //this is not working even if the user does not exist.
    }

How do I come around this?

5
  • 1
    What does console.log( detail ); give you if you call it inside the Error segment? Commented Apr 15, 2014 at 13:12
  • @Khôi: the echo is just once. It echoes once based on the condition that is met: whether a student found in the DB or not. Commented Apr 15, 2014 at 13:17
  • @hjpotter92: It shows [object Object]. Commented Apr 15, 2014 at 13:19
  • Using chrome and console.log(detail) you can see the object and it's properties. Commented Apr 15, 2014 at 13:29
  • dont you mean console.dir()? Commented Apr 15, 2014 at 13:39

1 Answer 1

2

Your scripting will fail at the moment you're checking detail.Name.length. The error will stop Javascript from executing the rest.

In case of an error your JSON data will look like this:

   {"Error":"No record for this user."}

if you then run your JavaScript code:

if(detail.Name.length>0) 

... Javascript will come back with "Uncaught TypeError: cannot read property 'length' of undefined..." and it will STOP EXECUTING all other JavaScript code, thus it never gets to your error handler.

to solve this, don't check the length of a record before you know it exists:

if(typeof detail.Name!="undefined" && detail.Name.length>0){
   ... etc... 

In this case you don't even have to check the lenth, if "name" is set you know it was set by your PHP script...

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

1 Comment

Alternatively, 'Error' in detail and 'Name' in detail

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.