Skip to main content

How to get json data from a file (jQuery)



Just cant figure it out. I have a large object stored as a JSON file and I want to access it once and use it multiple times:







var myjson = new Object();

$.getJSON("myJSON.js", function(json) {

myjson = JSON.stringify(json);

});

$('#console').append(myjson);







This does nothing. It's a scope issue, I know. I just don't know how to do what I'm wanting. Must I do all my functions inside the $.getJSON call or is there a way to pass the object that I can use throughout runtime?


Comments

  1. It's a scope issue, I know.


    No, it's not a scoping issue. It's an issue with your understanding about how AJAX works. AJAX is asynchronous. This means that when you send an AJAX request, the function that sent this request ($.getJSON in your case) returns immediately. It is only inside the success callback that you should use the results. This callback function could be called much later. It doesn't really depend on you at what moment in time in the future this might happen. Might never happen actually if there is an error on your server.

    So the only place where you could reliably consume the results that the server sent after an AJAX call is inside the success callback:

    $.getJSON("myJSON.js", function(json) {
    // here and only here you can access the results of your AJAX call.
    $('#console').append(JSON.stringify(json));
    });


    There are some horrible things that you could do like performing synchronous calls to the server:

    var myjson = { };
    $.ajax({
    url: 'myJSON.js',
    dataType: 'json',
    async: false,
    success: function(json) {
    myjson = JSON.stringify(json);
    }
    });
    $('#console').append(myjson);


    The async: false option makes a synchronous call. Obviously this completely defeats the whole purpose of AJAX as it will freeze the browser during this call. You are probably better of directly including the myJSON.js as a script tag:

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


    Another benefit you might get from this approach is that the browser will ensure for you that this script is completely loaded before executing any other scripts. So the following could work fine:

    <script type="text/javascript" src="myJSON.js"></script>
    <script type="text/javascript">
    var myjson = someJavascriptVariableThatYouDeclaredInMyJSON;
    </script>


    and then later:

    <script type="text/javascript">
    $('#console').append(JSON.stringify(myjson));
    </script>

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.