following from javascript jquery and using eval i still could not get jquery to read the data asynchronously.
data1=[1,2,3,4]
Note: i have included async:true in the below example just to show the difference
Below example return "null"
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:true,
});
return result;
};
})
and below example work fine and gives the result in an array i.e [1,2,3,4]
$(document).ready(function(){
var myArray=[];
myArray=getValues();
alert(myArray);
function getValues(){
var result=null;
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;},
async:false,
});
return result;
};
})
can someone explain how to get the results asynchronously Thanks
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
AJAX is still relevant and very popular, but how you write it may change based on what libraries or frameworks are in the project. I almost never use the "raw" JavaScript way of writing it because jQuery makes it easier and is almost always already loaded into a project I'm working on.
What is jQuery ? jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM) and JavaScript.
I would change it to this ...
$(document).ready(function(){
function postProcessing(data) {
var myArray = data;
alert(myArray);
}
getValues();
function getValues(){
$.ajax({
url: 'data1.html',
type: 'get',
dataType: 'json',
cache: false,
success: postProcessing,
async:true,
});
};
})
This should work, as it has worked in mine, but i suggest you not to do it.
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
/*don't do your stuff here*/
/*do inside success*/
function getValues(){
var result=null;
$.ajax({
url: 'phpinfo.php',
type: 'get',
dataType: 'json',
cache: false,
success: function(data) { if(data != null){ alert(data); } },
});
return result;
};
})
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With