0
<html>
<head>
    <title>Group Test</title>
    <script type="text/javascript" src="/static/javascript/jquery-1.8.2.min.js"></script>

</head>
<body>

    <script type="text/javascript">

    var global = new Array();
    $.ajax({
        url: "/json",
        success: function(reports){
            global = reports;
            process(reports);
            return global;
            }
        });


function process(reports){
    for (i=0; i<reports.length; i++) {
        document.write(i + " : "+reports[i].fields.report_name+"<br>");
        }
    }

    </script>

</body>
</html>

OK, so there is my code. I am trying to use the JSON data throughout my code, but for some reason, I get a "reports is undefined" error whenever I try to use the reports object outside of the $.ajax() function.

According to JSLint, the code looks good, AND lists both the reports and the variable global as global variables.

If I try to run anything that uses either of those outside, it won't work.

'success'(reports)
global
global
line 22
process(reports)
global
document
1
  • Oh yeah, screw the existing global properties. Let's just pollute the global namespace with our own variables. We don't need some stupid IIFE wrapper. :P Commented Oct 5, 2012 at 20:09

2 Answers 2

1

You can not access reports as global object only global can be accessed from every place. reports is a local variable to success as well as for process function

<script type="text/javascript">

    var global = new Array();
    $.ajax({
        url: "/json",
        success: function(reports){
            global = reports;
            process(reports);
            return global;
            }
        });


function process(reports){
    for (i=0; i<reports.length; i++) {
        document.write(i + " : "+reports[i].fields.report_name+"<br>");
        }
    }
        // reports is undefined here. but global can be accessed (will be empty array before success function get called)
    </script>
Sign up to request clarification or add additional context in comments.

Comments

0

Keep in mind $.ajax is async, so unless you call your functions inside the success callback, the value might not be set yet.

Also you'd need to use global not reports.

1 Comment

I'm also curious if i chose to return "reports" would it then become available?

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.