dcsimg
www.webdeveloper.com
Results 1 to 4 of 4

Thread: Setting variables equal to each other

  1. #1
    Join Date
    Jan 2017
    Posts
    5

    Setting variables equal to each other

    So I'm just now starting with JS and I was wondering why this code doesn't work.

    Code:
    	var json = [];
    
    	$.getJSON('https://api.coinmarketcap.com/v1/ticker/', function(result) {
    
    		for(var i = 0; i < 10; i++) {
    			json.push(result[i]);
    		}
    
    		console.log("This is the json", json);
    
    	});
    
           console.log("This is the json2", json);
    The log inside of the $.getJSON works just fine, but even though I'm adding to the json array it will not print out the 10 elements when I print it outside of the $.getJSON function.

  2. #2
    Join Date
    Dec 2012
    Posts
    1,583
    This is a common subject of confusion: Ajax and getJSON are working asychronously, i. e. a request is sent to the server first and a short time later the response arrives and the callback function is called. Immediately after the call the response has not yet arrived and the data is not available.

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,522
    It is also a common mistake that people post JQuery as JavaScript...

    Moved to JavaScript Frameworks.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  4. #4
    Join Date
    Aug 2017
    Location
    Bulgaria
    Posts
    17

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center