0

I recently refactored my javascript/jquery application code to use the module pattern.

I have two modules, lets say A and B.

Module B contains a public method(say, Bmethod) that makes a jQuery AJAX JSONP call($.ajax) and passes the response in a callback.

Inside Module A there is a call to B.Bmethod() with a callback function to handle the returned response.

Here is module B's definition:

var B = (function()
{
  var obj = {};
  obj.Bmethod = function(data, callback)
                {
                  //do JSONP AJAX call
                  callback(response);
                }
  return obj;
}());

Now, here's module A's definition with the method call on module B

var A = (function()
{
  var doAjax = function(data)
  {
    B.Bmethod(data, function(response)
    {
       //Do something with the response
    });
  }    
}());

Here's how I load the module A and start the code execution:

$(document).ready(function()
{
   A.doAjax(data);   
});

The problem here is that, I have different behavior on Chrome and Firefox. On Chrome, the AJAX call is not being executed at all. There is no request sent. However, on Firefox, I can see the request made and also get a response back, but I do not receive a success callback.

If I put all of this code outside of modules, in just one single file, everything seems to work properly.

I have seen a lot of people(on StackOverflow as well) using the module pattern with AJAX calls successfully, but have not been able to figure out what I am doing wrong.

Any ideas/solutions?

gofeddy
  • 579
  • 8
  • 20
  • Are you testing this locally? If you are, this is a cross-origin problem. Try testing it on a server or launch Chrome with the `--allow-file-access-from-files` parameter. (you will need to close all open Chrome windows before launching with it) – TheZ Jul 06 '12 at 16:56
  • I am testing this on my local Tomcat server with the response coming back from a web server that supports cross-domain requests. I can get this to work if I don't use modules at all. i.e if I have all of the code under $(document).ready(){}. Could it be something to do with my way of using modules? – gofeddy Jul 06 '12 at 17:01
  • how are you loading these modules? – Kishore Jul 06 '12 at 18:20
  • I edited the code in my question to show how I am loading my main module and calling the methods. – gofeddy Jul 06 '12 at 18:53

1 Answers1

0

Fixed the problem.

I was actually having a duplicate copy of the same AJAX request($.ajax) in a different file. So, when the request was being made, I am assuming the duplicate was (also)being called, and maybe this was causing inconsistency issues. However, on Chrome, setting a breakpoint showed no signs of the duplicate being called.

For now, I removed the duplicate request and it works fine. But, I still don't understand why there was an inconsistent behavior between Chrome and Firefox.

gofeddy
  • 579
  • 8
  • 20