function returns after an XMLHttpRequest

Posted by ashays on Stack Overflow See other posts from Stack Overflow or by ashays
Published on 2010-05-14T14:41:42Z Indexed on 2010/05/14 16:04 UTC
Read the original article Hit count: 241

Filed under:
|
|

Alright, I know questions like this have probably been asked dozens of times, but I can't seem to find a working solution for my project. Recently, while using jQuery for a lot of AJAX calls, I've found myself in a form of callback hell. Whether or not jQuery is too powerful for this project is beyond the scope of this question. So basically here's some code that shows what's going on:

function check_form(table)
{
  var file = "/models/"+table+".json";
  var errs = {};

  var xhr = $.getJSON(file, function(json)
  {
    for (key in json)
    {
      var k = key;
      var r = json[k];
      $.extend(errs, check_item("#"+k,r));
    }
  });
  return errs;
}

And... as you can probably guess, I get an empty object returned. My original idea was to use some sort of onReadyStateChange idea that would return whenever the readyState had finally hit 4. This causes my application to hang indefinitely, though. I need these errors to decide whether or not the form is allowed to submit or not (as well as to tell the user where the errors are in the application. Any ideas?

Edit. It's not the prettiest solution, but I've managed to get it to work. Basically, check_form has the json passed to it from another function, instead of loading it. I was already loading it there, too, so it's probably best that I don't continue to load the same file over and over again anyways. I was just worried about overloading memory. These files aren't absolutely huge, though, so I guess it's probably okay.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript