0

I am declaring windows.uris outside any function, then i'm adding elements in $.each(), at the last line when alerting window.uris is empty. Why ?

window.uris = new Array(); 

window.groups = new Array();

jQuery(document).ready(function($) {


host = document.location.host,
path = document.location.pathname;
url = host + path;
var domg = new Object();
var optgroup;
var productsDom = "";

  if (contains(url, 'manage/items.php')) {
    $.post('http://localhost/frontaccounting/proxy.php',
    {
        "url":"http://localhost:8081/stock/categories/",
        "m":"get",
        "data": ""
    },
      function (data) {
        d = $.parseXML(data);
        $xml = $( d );

        $xml.find("category").each(
            function (i,e) {
                optgroup = '<optgroup label="'+ $(e).children("name").text()+'">';
                categoryId = $(e).children("id").text();
                auxx =  (categoryId*1);
                window.uris[i]="http://localhost:8081/stock/categories/" + (auxx );
                window.groups[auxx + ""] = optgroup;
            }
        );
    }
    );  
    //sleep(2000);
        alert('URI' + window.uris);
2
  • you should do the alert inside the post callbac, here it get called before window.uris is feed Commented May 14, 2012 at 11:31
  • Your ajax is asynchronous. If you put another alert inside the $.post callback, you'll notice that it is alerted after the current one. Commented May 14, 2012 at 11:32

1 Answer 1

2

In your function you make an asynchronous call to some url. The alert command, however, is inside your function and not inside the callback.

So it will be called immediatly instead of waiting until the AJAX-request has finished and your data is present.

A simple solution is to move your alert inside the callback-function.

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

2 Comments

I implemented a sleep function function sleep(ms) { var dt = new Date(); dt.setTime(dt.getTime() + ms); while (new Date().getTime() < dt.getTime()); } . And it does not matter how much i wait before the alert() at the end
@Blitzkr1eg A sleep function at that point is far from optimal. What happens, if your request takes a little longer for whatever reason? Put your further logic inside the callback function or call another function from there to make sure the request is actually completed, before using the data!

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.