Javascript array access outside function - javascript

I'm trying to get json data with $.getJSON and it's working fine.
This is my code:
$(document).ready(function(){
var MainArray = new Array();
$.getJSON('check-location.php?onload=true', function(result) {
$.each(result, function(i){
MainArray[i] = result[i].CountryName;
});
});
$(".drop-down").append("<div>" + MainArray[0] + "</div>");
});
I'm trying to assign it to array for later usage, but when I try to access it and display it I get undefined.
I get all the data for sure, but when I assign it to MainArray I cant access it outside the $.each function and I've no idea why.

That's because Ajax is asynchronous, you are trying to append a non-existent value:
$.getJSON('check-location.php?onload=true', function(result) {
$.each(result, function(i){
MainArray[i] = result[i].CountryName;
});
$(".drop-down").append("<div>" + MainArray[0] + "</div>");
});

Because $.getJSON is asynchronous, the MainArray isn't updated until the data is successfully returned.
But, the line
$(".drop-down").append("<div>" + MainArray[0] + "</div>");
will have already executed before the $.getJSON is completed...hence it is undefined.
You should move this somewhere and execute it when your data has returned, ie. in the callback

Like every body said, because its an asynchronous request
you can turn that off (not a very good practice, but it will fix the problem)
Add this before the $.getJSON call
$.ajax({ async: "false" });

Related

Fetching local text file and assign contents to a variable

For as simple as this should be, I have no idea what I am doing wrong. I'm attempting to fetch a local text file and store it in a variable, but regardless of the method (fetch api, $.get and ajax) I use, I always get undefined.
$(document).ready(function() {
var fileConfiguration;
$.get( "Configuration.h", function( data ) {
fileConfiguration = data;
});
document.getElementById("demo").innerHTML = fileConfiguration;
});
The data variable is properly fetched, I can use alert or console.log and see the contents correctly. When I assigned it to a variable though, it's undefined. I imagine this has something to do with it being an asynchronous callback, but can't figure out the problem.
As you and #charlietfl have pointed out the AJAX request is asynchronous which means that the last statement in your code is executed before there's a response, hence fileConfiguration is still undefined.
Therefore the best place to do the assignment is inside the callback like so:
$(document).ready(function() {
$.get( "Configuration.h", function( data ) {
document.getElementById("demo").innerHTML = data;
});
});

Output html from ajax/jsonp request using jQuery

I'm trying to output html using an ajax request from a jsonp file . When using console.log I'm seeing the data looping fine, however when using a variable to grab the loop and output in html, I'm only seeing one result. What am I missing?
$.ajax({
url: "http://sitedotcom/blog/json",
dataType: "jsonp",
jsonpCallback: "jsonpCallback",
success: jsonpCallback
});
function jsonpCallback(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key]["title"] + ", " + data[key]["entry_id"]);
rssData = '<h2>' + data[key]["title"] + "</h2><p>" + data[key]["blog_summary"] + "</p>";
}
$('#blog-content').html(rssData);
}
}
You have $('#blog-content').html(rssData); inside the loop....so only the last result will show since html() replaces all content.
Try using append() instead or concatenate rssData each iteration and set html() after loop completes
It looks like rssData is out of scope when you are adding it to your #blog-content. Also you are outputting different data when doing your console log and setting your rssData variable.
If you could provide the json layout and also the html layout you are trying to append to.

Retrieve variable set within getJSON callback function

I am forced to use data from within the getJSON callback function outside of that function. Have a look:
$('#stars').raty({
score: function() {
var $value = 0;
var $id = <?=$id?>;
$.getJSON("getuserrating.php?id=" + $id, function(data) {
$.each(data, function(key, val) {
$value = val;
});
});
return $value;
},
});
This is what I tried but it failed, the $value is still set to 0, although inside the callback it's definitely set to an actual value. I know why it fails, because the AJAX request is send asynchronously. The problem is, the correct way, doing everything inside the callback, is not possible. As you can see I need to retrieve the JSON object within the raty (a plugin) setup. I would just use $.ajax() and set that to synchronous but the documentation marks this as deprecated for 1.8. I'd rather not introduce a solution that I know will be deprecated in the future.
Is there any way at all to do this? Maybe I just don't see the forest for the trees and there's an easy solution right before me. Thanks in advance :)
Approach is backwards if you need to use ajax to get the score.
Make the ajax call first, then pass the value to score within the ajax success
$.getJSON("getuserrating.php?id=" + $id, function(data) {
/* pseudo code here since I don't know the plugin and it's data requirments*/
var score= data.score;
$('#stars').raty({
score: score
});
});
EDIT: you can still pass the data into a score function this way also
Maybe this (taken from jquery getJSON api doc http://api.jquery.com/jQuery.getJSON/) could work:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
Just assign another raty attribute instead of returning.

jQuery to load text file data

I'm trying to load data from a text file on my server using the $.get() function in an external script file. My code is as follows:
/*
* Load sample date
*/
var stringData;
$.get("http://localhost/webpath/graphing/sample_data.txt", function(data){
stringData = data;
//alert("Data Loaded: " + stringData);
});
//Split values of string data
var stringArray = stringData.split(",");
alert("Data Loaded: " + stringData);
When I'm inside the $.get() function I can see stringData var get peopulated just fine and the call to alert confirms that it contains data from the sample text file. However, when I get outside the $.get() function, the stringData var no longer shows. I don't know enough about how the function works to know why it is not doing as I expected. All I want it to do is load the text data into a variable so I can work with it. Any help is appreciated.
get is asynchronous meaning it makes a call to the server and continues executing the rest of the code. This is why you have callback methods. Whatever you intend to do with the return data do it inside the callback method(where you have put the alert).
get, post are all asynchronous. You can make a synchronous call by using
using $.ajaxSetup({ async: false }); anywhere in your code. This will affect all ajax calls in your code, so be careful.
$.ajax with async: false e.g. shown below.
Look at the below code and the API docs link mentioned above to fix your problem.
/*
* Load sample date
*/
var stringData = $.ajax({
url: "http://localhost/webpath/graphing/sample_data.txt",
async: false
}).responseText;
//Split values of string data
var stringArray = stringData.split(",");
alert("Data Loaded: " + stringData);
The $.get function is asynchronous. You'll need to do any work on the returned data in the callback function. You can move that function to not be inline to clean up the code as well.
function parseData(data){
//do something with the data
alert("data is: " + data);
}
$.get("http://localhost/webpath/graphing/sample_data.txt",parseData);

Pushing to Javascript Array from Jquery JSON request

Why does this code always return 0?
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length);
Though I can move or add "alert(possibleMatches.length);" inside the $.each and it will output the correct number of elements.
I'm just curious as to why it the values aren't going into the array as I expected. I'm sure its a local variable vs. global variable issue, just not sure why.
Basically, what this is trying to do is fill the possibleMatches array with the data results.
thanks!
Asynchronicity. The line alert(possibleMatches.length); executes before the success callback for $.getJSON() executes.
So, to have your alert report accurately, just move it.
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
// To here
alert(possibleMatches.length);
});
// From here
Remember, the first A in AJAX stands for "Asynchronous"
$.getJSON performs an asynchronous call, whose callback is executed on completion of the xmlhttprequest used:
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) { // <-- this will run later
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length); // this will call immediately
The jetJSON request is asynchronous, it finished after your alert runs. If you want an accruate alert, it should be in your callback for getJSON like this:
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
});
alert(possibleMatches.length);
});

Categories

Resources