2

I'm having a problem with jQuery when using it within a selfdefined function.

When I'm starting my jQuery right from my .html like:

<script type="text/javascript" src="js/MyJS.js"></script>

MyJS:

$.getJSON('MyFilePath', function(data)
{
  var items = [];
  $.each(data, function(key, val)
  {
  //Doing things with my data.
  });
 });

it works fine and returns me my file. (I'm using plain text file with a json structure).

But when I'm trying to start it from a function e.g.:

function getAllDepts()
{
  $.getJSON('MyFilePath', function(data)
  {
    var items = [];
    $.each(data, function(key, val)
    {
    //Doing things with my data.
    });
  });
}

it won't work. It seems like he's not able to load my file but I just don't get why.

With:

$.ajax({
             url: "MyFilePath",
             success: function(data){
             console.log(data);
             },
             error: function(data){
             alert(error);
             }
             });

I'd be still able to get my data but I just want to know why getJSON doesn't work. I read that getJSON has its problems with loading local files but I'm not sure if it applies to my problem.

Any ideas?

@comments:

  • Yes I'm calling the function through an onclick:"getDepts()" in my .hmtl and it gets called correctly.
  • The return value is one step ahead because the getJSON is not working correctly. It's not a problem mit jQuery thought, since when debugging with Firebug(Firefox) the method gets called. The main problem seems to be he's not able to load the file.
  • My data file is an .txt. with json structure. (I checked my json structure with http://jsonlint.com/ and it said its okay)
  • There's no error like 404 since the files are stored locally and no errors show up while using firebug.
  • I created the syntax error while editing this post. Fixed the braces.
blaluma
  • 185
  • 1
  • 2
  • 15

2 Answers2

1

Your function doesnt look right try

function getAllDepts() {
    $.getJSON('MyFilePath', function(data) {
        var items = [];
        $.each(data, function(key, val) {
            //Doing things with my data.
        });
    });
}
Mark Broadhurst
  • 2,675
  • 23
  • 45
  • Yes, you're right but it was only an error while creating this post here. In my programm I had the missing ");". – blaluma Apr 04 '13 at 06:45
0

Try the following. This may have something to do with the asynchronous nature of $.getJSON.

(document).ready(function() {

    function getAllDepts()
    {
      $.getJSON('MyFilePath', function(data)
      {
        var items = [];
        $.each(data, function(key, val)
        {
        //Doing things with my data.
        });
      });
    }

}
spitz
  • 658
  • 1
  • 8
  • 19