1

I am having trouble with jQuery with trying to modify a global variable from within the success callback:

<html>
<head>
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript">

  // Define items in the global scope
  items = null;

  // Get items from XML for a given category ID
  function getItems(categoryID)
  {
    $.ajax({
      type: 'GET',
      url: 'items.xml',
      dataType: 'xml',
      success: function(xml){
        items = $(xml).find('category[id="'+categoryID+'"]').children().first();
        // This works (returns the name of the first item)
        alert( items.attr('name') );
      }
    });
  }
</script>
</head>

<body>
<script type="text/javascript">
  $(function(){
    getItems(1);

    // This doesn't work (returns null)
    alert( items.attr('name') );
  });
</script>
</body>

</html>

What am I doing wrong?

1 Answer 1

3

This is because the callback hasnt finished by the time you are executing the alert.

the Get request is asynchronous so execution continues even if it has not finished. So when the alert() statement executes, the success callback has not yet executed, therefore items is still null.

You can either do a synchronous call, or include whatever you are trying to do inside the success callback.

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

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.