Fetching local text file and assign contents to a variable - javascript

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;
});
});

Related

Can't get Ajax response

I am using javascript and php to run an Ajax code.
The result at the moment is undefined.
I am using localStorage to move the variable from the Ajax function because I cannot understand the use of a callback (I have followed numerous examples of using callbacks but none ever worked. I figured this solution might be the least complex.
Javascript:
$( document ).ready(function() {
$('#submit-values').click(function(e){
/************************************************************* SUBMIT */
e.preventDefault();//Stop page reload on click
$('#put-output-here').val(createParagraph());
});
function createParagraph(){
createSentence();
return localStorage.getItem('sentence');
}
function createSentence(){
$.when(ajax1()).done(function(a1){
localStorage.setItem('sentence', a1);
})
}
function ajax1(){
$.post("word-engine.php",
{
},
function(data){
});
}
});
PHP:
<?php
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for($x = 0; $x < 10; $x++){
$rand = rand(0,62);
$randomString = $randomString.$chars[$rand];
}
echo $randomString;
?>
At the moment my result is undefined
use this: since $.post is a asynchronous function. The control from function will immediately return after it run post but the response from post may be received later.
function ajax1(){
$.post("word-engine.php",
{
},
function(data){
setdata(data);
});
}
function setdata(data){
localStorage.setItem('sentence', data);
}
note: for more info see this post:why cant I return data from $.post (jquery)
You need the done event on the $.post function not on the function that's wrapping that function.
E.g.
$.post( "word-engine.php", function( data ) {
localStorage.setItem('sentence', data );
});
On 'done'/return of the ajax post it will put the returned value into your localStorage 'sentence' key. The first param of the post function is the URL of the endpoint, the next is the success handler function. You can then specify more including the callback function handler for failure etc. See docs here for more information.
#suchit makes a good point, you won't be able to access the value in localStorage straight away because post is an async event, the javascript code will move on and the callback will happen when the response is received. You're best displaying your returned localStorage variable to screen inside the success handler or trigger whatever needs to happen with it from there.

getJSON jQuery won't fill object

So I've got some code that retrieves a series of objects from an API. When I try to store them in a global variable, it doesn't seem to do anything. Here's the code:
var current_corpus = {};
function page_init() {
$.getJSON("http://resource1.com", function(data) {
populate_collections(data);
populate_citations(data);
});
}
function populate_collections(collections) {
$.each(collections, function (i, item) {
current_corpus[item] = [];
});
}
function populate_citations(collections) {
$.each(collections, function (index, collection) {
$.getJSON("http://resource2.com/" + collection.collection_id, function(data) {
current_corpus[collection] = data;
console.log(current_corpus);
});
});
}
When this finishes, current_corpus is completely empty. Logging these items verifies that they're being returned from the resources I'm posting to. I think there's just something about the asynchronous nature of these calls that I'm missing.
The line
current_corpus[item] = [];
is superfluous I think as the line
current_corpus[collection] = data;
should do the same thing while also tying data to the key object. Either way at the end of these functions running trying to access current_corpus via the console just gives me back an empty object.
Resources for dealing with AJAX stuff like this would be appreciated as well.
It all depends on what you want to do when the ajax requests complete. The A in ajax stands for Asynchronous meaning that such requests are non-blocking -- i.e. they will run in the background as control moves to the next line. Which explains why you're seeing an empty object right after the functions that invoke the ajax requests.
You can confirm that your code is working fine or you can do something once all the requests complete by using the following code snippet:
$(function() {
$(document).on('ajaxStop', function() {
console.log( current_corpus );
//do something with the now fully constructed object
});
});

jquery - scope getting lost in variable

I am developing application which will get some dynamic content which is irrelevant to my question. and the question is
var pat;
$.post('venki/path.jsp', { nam:nam } , function(data) {
pat=data;
alert(pat); //it will displayed the received code form path.jsp
});
alert(pat);// it will not keep the data received from path.jsp
Now I need to not lose the scope.
For example:
var pat=0;
$.post(
pat = 1
);
alert(pat);
It should alert 1 and not o
In java, i should use static. In jquery, how to declare static variables.
Got an answer:
Its simple and very useful and no need to worry about synchronous. the answer is tricky...
it is because post request is not completed when you are alerting pat value. To ensure that value is modified, alert it inside post success function:
var pat;
$.post('venki/path.jsp', { nam:nam } , function(data) {
pat=data;
alert(pat); //modified value
});
If i'm not mistaken, the $.post is async so the pat is not losing it's scope but executed before the pat=data executed
To make it synchronous call look at this question: how to make a jquery "$.post" request synchronous

How to access variable inside a block

I have an AJAX request:
var foo = [],
parse = '';
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
});
Now the string parse is the data that I want. How can I access that data? I tried showing it using alert(), but it's not displaying anything. I think this has to do with the variable scope.
How can I get that data?
parse looks like a global variable so it will be available anywhere. The issue is probably when you're trying to access it. You can ONLY access parse in your .done() handler or some function you call from that.
The reason for this is that your ajax call is asynchronous. That means that the operation starts, the rest of your javascript continues to execute and then SOMETIME LATER the ajax call completes and ONLY then is the parse variable valid. Because of this, there really is no reason to declare the parse variable the way you have. You should just use its value inside the .done() handler.
This is asynchronous programming and works differently than synchronous, sequential programming. You must use asynchronous programming techniques with asynchronous ajax calls.
If you try to access parse inside the .done() handler and it's still empty in there, then the issue is likely that data.item isn't what you think it is and maybe isn't triggering the .each() loop and thus nothing is getting put into foo or parse. To debug this case, you should look at what exactly is in data and data.item.
This would be my suggestion:
$.ajax({
type: "GET",
url: "some/path/",
data: somedata
}).done(function( data ){
// no reason for these variables to be wider scope than here
var foo = [], parse;
$.each(data.item, function(i, value){
foo.push(value);
});
parse = foo.join(', ');
// look at parse here
console.log(parse);
// if parse still empty, then look at data and data.item here
// to see what they are for debug reasons
console.log(data);
console.log(data.item);
// now, you can use parse here
callSomeFunction(parse);
});

How Do I return a javascript variable from a function that contains a $.get() request

I've tried Googling this but could not reslove it. It may seem like a really simple issue to others but I'm baffled by it. I have the below code in which I get undefined for the first alert but I still get the correct values in the 2nd alert. BUT if I comment out the first alert (just the line with alert) then the 2nd alert output becomes undefined. Can any one explain why this is and how I may output the 2nd alert correctly without the first one, any Help is greatly appreciated.
function getDetails(ID){
var qArray = [];
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
});
//First Alert
alert("-> "+qArray[0]);
return qArray;
}
This is the 2nd alert which calls the above method:
var myArray = getDetails(4);
alert("myArray [0]: "+myArray[0]);
You can't return a value, the $.get() call is asynchronous.
You need to defer any operations on qArray until the AJAX call has completed, i.e. inside the callback.
Better yet, use deferred callbacks:
function getDetails(ID) {
return $.get('get_Question', {"Id":ID})
.pipe(function(json) {
return [json.value1, json.value2];
});
}
The .pipe deferred function creates a new promise which will ultimately return the desired array, but only once the AJAX call has completed.
You would then use this like this:
getDetails(ID).done(function(qArray) {
alert("-> " + qArray[0]);
});
Note that $.get() doesn't directly support error callbacks, but with deferred objects you can get access to them:
getDetails(ID).done(function(qArray) {
alert("-> " + qArray[0]);
}).fail(function(jqXHR, textStatus, errorThrown)) {
alert("The AJAX request failed:" + errorThrown);
});
Without this you'd need to build the error handling directly into the getDetails() function and then require some mechanism to tell the rest of the application logic about the error.
NB I've assumed that you don't really need to call JSON.parse() manually - if your web server returns the right Content-Type header then jQuery will do that for you automatically.
Ajax calls happens asynchroniusly, meaning you can't wait for the call to return and get the value. The way to do it is to employ a callback. Your example will become something similar to this:
function getDetails(ID, callback){
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var qArray = [];
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
callback(qArray)
});
}
Calling it will change a bit:
getDetails(4, function (myArray) {
alert("myArray [0]: "+myArray[0]);
});
The First Alert is called before the ajax call is finished, so the variable is still undefined.
This is because the $.get() is done asynchronously. There is no option for $.get() to pass parameter for async calls, so you should use $.ajax() instead and pass a param async: false
The $.get call creates a new asynchronous request for the resource in question.
When you call the first alert it is undefined because the request hasn't been completed yet. Also since you are forced to pause on the alert the request has time to be completed in the background. Enough time for it to be available by the second alert.
The same thing happens when you comment out the first alert. This time the second alert is called before the request is completed and the value is undefined.
You need to either make your requests synchronous or consider continuing execution after receiving the response by using a callback function within the success callback function you have already defined in $.get.
As several others have said, ajax-request are asynchronous. You could however set the async property to false to get a synchronous request.
Example:
function getDetails(ID) {
var result = $.ajax('get_Question', {
async : false,
data : { 'Id' : ID }
});
// do something with the result
return result;
}
I myself would have use a callback function instead beacuse async:false is bad practice and is also deprecated.
You'll need to rewrite $.get to use $.ajax and specify async: false
AJAX is asynchronous: you can't tell when the request will complete. This usually means you need to pass callback methods that will be called with the result of the request when it completes. In your case this would look something like:
function getDetails(ID, callbackFunc){
$.get('get_Question', {"Id":ID}, function(){})
.success(function(data){
var qArray = [];
var json = $.parseJSON(data);
qArray.push(json.value1);
qArray.push(json.value2);
callbackFunc(qarray);
});
}
getDetails(4, function(qArray) {
alert("myArray [0]: "+qArray[0]);
};

Categories

Resources