0

I want to test if the data array in the code below has content, because when a user gives a packageid (variable in the code below) that doesn't exist i want the else from the "if...else" to be executed. When i put in a packageid that exists everything works fine, but when i put in no number or a number that doesn't exist, the else side does't get evaluated.

function getInfoAndStatus(){

sym.$("customer_name").empty();

packageid = $("#tracknrfield").val();

var url = "http://student.howest.be/sylvain.vansteelandt/fedex/server/getPackageTracking.php?id=" + packageid;

$.getJSON(url,function(data){
    if(data && data[0].id){
        $("<span />", {
    text: "Customer name: " + data[0].customer_name + " " + data[0].customer_firstname
}).appendTo(sym.$("customer_name"));
    } else {
            $("<span />", {
    text: "The package with number " + packageid + " has not been found. Please try again."
}).appendTo(sym.$("customer_name"));
    }
});
}

getInfoAndStatus();
1
  • So are you asking if it's possible to test if data has any values? Commented Aug 29, 2013 at 0:31

2 Answers 2

2

Check your javacript console for any errors. data may be null or an empty array.

Adding a check for console.log(typeof data) may be useful as well.

Sight unseen, I'd most likely do something like if (data && data.length > 0)

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

1 Comment

thank you, I used if (data && data.length > 0) and that worked perfectly.
0

If you check your console output, I'm betting you'll see an error there.

Your if check should look like:

if(data && data[0] && data[0].id)

As you may not have an element in your array.

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.