0

I'm trying to select a row from a json array using jquery. This is what i have:

$(document).ready(function() {

    $.getJSON( "js/collectie.json", function(data) {
        jsoncollectie = data;
    })

    $( "#collectie li" ).click(function(){

        var thumb_id = $(this).data("id");

        for(var i = 0; i < jsoncollectie.stoelen.length; i++){

            if(jsoncollectie.stoelen[i].ref == thumb_id){
                $("#detailimage").attr('src', jsoncollectie.stoelen[i].image);
                $("#detailimage").attr('title', jsoncollectie.stoelen[i].title);
                $("#title").html('<h4> '+jsoncollectie.stoelen[i].naam+' </h4>');
                $("#secondaryimage").attr('src', jsoncollectie.stoelen[i].secondaryimage);
                $("#secondaryimage").attr('title', jsoncollectie.stoelen[i].secondarytitle);
                $("#description").html('<p> '+jsoncollectie.stoelen[i].description+' </p>');
            }   
        }
    });
});

Now when i click on a list item (#collectie li) the console outputs "ReferenceError: jsoncollectie is not defined". I don't know why it's doing that and i'm pretty sure it worked two weeks ago. Don't know much about javascript/jquery yet, but i'm slowly learning.

4
  • 1
    What if you add var jsoncollectie =[]; before $.getJSON ... ? Commented Sep 25, 2014 at 16:26
  • 1
    you missed a semicolon after the getJSON call. probably isn't your issue, but i've seen weirder things happen Commented Sep 25, 2014 at 16:28
  • @MaximHash: then the console outputs "TypeError: jsoncollectie.stoelen is undefined". Commented Sep 25, 2014 at 16:56
  • 1
    @BrettWeber: Thanks, added it but doesn't fixe the problem as you said. Commented Sep 25, 2014 at 16:56

2 Answers 2

2
$(document).ready(function() 
{
    // Provide access to data outside of the getJSON call
    var m_oJsonCollectie = null;

    // Get the data
    $.getJSON( "js/collectie.json", function(data) 
    {
        // Set the data
        m_oJsonCollectie = data;

        // Apply the click handler
        $( "#collectie li" ).click(function()
        {
            var thumb_id = $(this).data("id");

            for(var i = 0; i < m_oJsonCollectie.stoelen.length; i += 1)
            {
                if(m_oJsonCollectie.stoelen[i].ref == thumb_id)
                {
                    $("#detailimage")   .attr('src',   m_oJsonCollectie.stoelen[i].image);
                    $("#detailimage")   .attr('title', m_oJsonCollectie.stoelen[i].title);
                    $("#title")         .html('<h4> '+ m_oJsonCollectie.stoelen[i].naam+' </h4>');
                    $("#secondaryimage").attr('src',   m_oJsonCollectie.stoelen[i].secondaryimage);
                    $("#secondaryimage").attr('title', m_oJsonCollectie.stoelen[i].secondarytitle);
                    $("#description")   .html('<p> '+  m_oJsonCollectie.stoelen[i].description+' </p>');
                }   
            }
        });
    });
});

JS have block level scope, so you wont get the values outside of the function unless you provide access to them or they are declared in global scope (which is considered bad practice).

This pattern should help you keep your data accessible, and only applies the click handler if the getJSON call is successful.

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

6 Comments

This is not correct. jsoncollectie is a Global variable because it is not declared using the var keyword, therefor it is not restricted by scope of a function. The provided code is not good practice, but it should work. This solution causes the JSON to be loaded on every click, which is not optimal
Yeah i've use similar code in the past but a friend pointed out the JSON would be loaded on every click, just as @BrettWeber said. This isn't ideal.
I tried the code nonetheless. Doesn't say anything about an undeclared var but the click event doesn't seem to work. I've added "console.log("test");" in the click function and it doesn't output in the console either.
@Boktor place a console.log message in the handler for getJSON, too, to ensure that the JSON value is being returned. Your issue would make sense if the JSON never came back at all
@BrettWeber: Indeed, i tried this: $.getJSON( "js/collectie.json", function(data) { jsoncollectie = data; console.log("json get"); }); but it does not output. No syntax errors though, and i'm 90% sure it worked when i first made it :(. No version control though, my bad. Any idea? Thanks so far!
|
1

Check that your getJSON request is being received and returned by using deferred methods

// Syntax that will shed light to your issue :
$.getJSON
(
    "js/collectie.json",
    function (oJSON) { /*success*/ }
)
.done(function()   { /* succeeded */ })
.fail(function()   { /* failed    */ })
.always(function() { /* ended     */ });

I came to this conclusion due to comments and the fact that a variable only declared in the success handler for getJSON was undefined. Since the JSON containing variable was undefined, the success handler must never have been called. Chances are that the path to the JSON you are trying to get is incorrect.

Documentation for the methods to accomplish :

UPDATE

Knowing that the response is 304, and the results are undefined are the important details here. This issue has been addressed by jQuery already here

This is actually correct, given the ifModified header has not been set to false.

To fix this issue, use ajaxSetup() to modify the header.

NOTE : the use of this method is not recommended by jQuery, but in this case it works.

// place this is document ready handler before making any calls.
$.ajaxSetup({ ifModified : false });

8 Comments

The path is definitely correct according to this i.imgur.com/MNLs3Zs.png and I've already tried messing with it. Not sure what 304 Not Modified response stands for though. Gonna try your code now will report soon.
As i thought. The request is failing, meaning that your data is not returned.. I am not completely sure why, though. :/
Looks good to me. I'll assume since answer was marked that this fixed your problem? :D
yeah, logistical error on my end but it worked with your code indeed! Sorry for the late answer and thanks again for all the help!
Its all god! Ad eel free to send a private message anytime! I'm good at what I do, and hopefully you'll be able to return the favor. The email on my profile is valid, I'll respond usually withing a couple days, a week at most.
|

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.