Ajax and scope problems - javascript

I'm having some problems with AJAX and the scope of my data. I am new to Javascript and I'm not sure how to fix my problem.
var urlList = new Array();
$.ajax({
url: "http://localhost:3000/url",
success: function(data) {
alert(data.expressions.url); //This shows the correct result
urlList[0] = obj.expressions.dom;
}
});
alert(urlList[0]); //this shows undefined
I need the data that is in urlList[0] so i can use it at a later time. I think it's a scope problem.
Could someone point me in the right direction please?
Thanks

It's not a scope problem, but a timing problem. The ajax method is executed asynchronously. That means that calling it will not cause your program to wait until it is finished. This results in the alert being shown before the request is finished.
To fix this, put the request inside the success function as well. This is the proper place to handle the results of the request.
var urlList = new Array();
$.ajax({
url: "http://localhost:3000/url",
success: function(data) {
alert(data.expressions.url); //This shows the correct result
urlList[0] = obj.expressions.dom;
// This might work now, depending on what `obj.expressions.dom` is. This
// isn't becoming clear from your code. Usually you would use the `data`
// parameter of the success function, which contains the response body of
// the ajax request that has just finished.
alert(urlList[0]);
// of course you can call other functions as well. For instance, you
// could call
urlListChanged();
// ..which you can declare in global scope. This way, you can repond to
// changes from multiple sources, without having to duplicate code.
// It will all work, as long as you use the success handler as the trigger.
}
});
function urlListChanged()
{
alert(urlList[0]);
}

Your problem is one of chronology.
$.ajax fires an asynchronous request, meaning the rest of your code after it will continue to be executed before the request has resolved. Since urlList is populated only once the request resolves, your alert is firing too early.
Change
$.ajax...
to
var req = $.ajax...
and wrap your alert in a success callback:
req.done(function() { alert(urlList[0]); });
...or just move the alert inside your existing success callback.

Related

Array contents don't change when used in a function in AJAX success

I'm using AJAX to parse json, everything works fine although when I try to call a function where I pass on the index value of the loop and then the funcion pushes this value into the Global array, It seems like it's not pushing these values even though console.log() prints out everything as it should on each step yet when I check the array length it's always at 0.
//This bit of code is actually inside a function and another ajax success
$.each(updatedData, function(index, element) {
$.ajax({
type: 'GET',
url: 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&redirects&callback=?&titles='+updatedData[index],
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log('success wiki');
//getting the pagenumber key value to use the extract value from it
var pagenum = Object.keys(data.query.pages);
if(data.query.pages[pagenum[0]].extract == null)
{
recycleData(index);
}
}
});
});
//this is the function which should push the trash value to the trashData
//the console.log actually logs all the correct values yet still doesn't push
function recycleData(trash){
console.log("sliced - "+trash);
trashData.push(trash);
}
//that's how the array is defined, it's obviously defined before all the functions just in case someone would ask
var trashData = [];
UPDATE: I have tested the array length after a delay, it is being populated after all the ajax requests have been completed yet I need other requests to wait for this request to finish so that the other requests will use updated data. This request is in another ajax success so keep that in mind.
If you want do other ajax on completion you can call your next ajax call on done function of previous ajax.
$.ajax({ ... }).done(second_ajax_fn);
Also you can set async:false but it is not recommended
The issue is likely that you're checking the value of trashData before the actual async requests are complete. If you want to ensure that all the requests are complete and then check it (or make more requests), you need something like jQuery Deferred - waiting for multiple AJAX requests to finish.

Global variables in jQuery plugin

I am creating a jquery plugin. In that am using some global variablse
$.rmtableparams.recordsCount: 0 is one of them.
I am assigned some values to this from one function inside an ajax call.
callAjax = function (surl, pselector, pi, rec) {
$.ajax({
..
success: function (data) {
$.rmtableparams.recordsCount =10;
}
});
}
But while I am trying to access $.rmtableparams.recordsCount in some other function it returns 0. But strange thing is that if i alert anything before that it will returns 10 correctly.
Ie: if my script is
alert("hi");
alert($.rmtableparams.recordsCount);
the second alert will shows 10
But if only alert($.rmtableparams.recordsCount); is there it returns 0
I was wondered with this. If any body knows the reason please help me.
The assignment $.rmtableparams.recordsCount =10; is inside the success callback of an $.ajax request. So the value isn't assigned until the ajax call is completed, and a response received. This happens fairly quickly, so while you're first alert is waiting to be closed, the ajax response is received, and the assignment is processed. Then, the second alert shows the new value.
If you leave out the first alert, the call is still being processed and the $.rmtableparams.recordsCount value hasn't changed yet.
It's as simple as that: AJAX stands for Asynchronous JavaScript And XML. Async is key, but often overlooked...
You can't just go ahead and set $.rmtableparams.recordsCount because $.rmtableparams doesn't exist.
You first need to set $.rmtableparams:
$.rmtableparams = {};
Then you go ahead and add data to the object:
$.rmtableparams.recordsCount = 10;
Make sure that the success callback is being fired. Add an alert or console.log inside the callback to do the check.

jQuery function execution order

I am having a problem, or perhaps a lack of understanding, with the jQuery execution order of $.get() function. I want to retrieve some information from a database server to use in the $.ready() function. As you all know, when the get returns, it passes the data to a return handler that does something with the data. In my case I want to assign some values to variables declared inside the ready handler function. But the problem is, the return handler of $.get() does not execute until after ready has exited. I was wondering if (a) am I doing this right/is there a better way or if (b) there was a way around this (that is, force the get return handler to execute immediately or some other fix I'm not aware of). I have a feeling this is some closure thing that I'm not getting about JavaScript.
As per request, I'll post an example of what I mean:
$(function() {
var userID;
$.get(uri, function(returnData) {
var parsedData = JSON.parse(returnData);
userID = parsedData.userID;
});
});
So as you can see, I'm declaring a variable in ready. Then using a get call to the database to retrieve the data needed. Then I parse the JSON that is returned and assign the userID to the variable declared before. I've tested it with a couple alerts. An alert after the get shows userID as undefined but then an alert in get's return handler shows it to be assigned.
$.get() is asynchronous. You have to use a callback to fill your variable and do the computation after the request is complete. Something like:
$(document).ready(function(){
$.get( "yourUrl", function( data, textStatus, jqXHR ) {
var myData = data; // data contains the response content
// perform your processing here...
registerHandlers( myData ); // you can only pass "data" off course...
});
});
// your function to register the handlers as you said you need to.
function registerHandlers( data ) {
// registering handlers...
}
$.get is an ajax request. A in AJAX stand for asynchronous, so script won't wait for this request to finish, but instead will proceed further with your code.
You can either use complete callback or you can use $.ajax and set async to false to perform synchronous request.
The $.get() function executes an async httprequest, so the callback function will be executed whenever this request returns something. You should handle this callback outside of $.ready()
Maybe if you explain exactly what do you want to do, it would be easier to help!
Are you looking for something like:
$(document).ready(function(){
var variable1, variable 2;
$.get('mydata.url', function(data){
variable1 = data.mydata1;
variable2 = data.mydata2;
});
});
If you declare the variables first, then you can set their values within the get call. You can add a function call at the end of the get handler to call a separate function using these values? Without some kind of example, its hard to go into any more detail.
Without seeing the full code, my guess is that you should declare your variable outside $.ready; initialize it in ready for the initial page load; then update it from the get callback handler.
for example
var x = ""; // declaration
$(document).ready(function() { x = "initial value"; });
$.get(...).success(function() { x = "updated from ajax"; });

How to make function that returns it's inner-function's value?

It's probably obvious to you, but I can't figure it out.
I need to make function that returns it's inner-function's value. In other words, I have function get_users() that must return JSON object. That JSON object is got by $.post (built-in jQuery).
function get_users() {
return
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
return response;
},
'json'
);
}
(above is what I tried to do, but it returned undefined - what a surprise)
Because of variable scope, I cannot just make variable in inner-function because it won't be visible in main function. I don't want to use global variables neither. Looking for better solution!
Thanks in any advice!
Why are you fighting against the asynchronous nature of AJAX? When you do AJAX you should get accustomed to work with events and callbacks instead of writing sequential code. You can't return the inner contents. The simple reason for this is that this inner function could execute much later than the outer function. So the outer function will return a result much before the success callback executes.
So here's the correct way:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// instead of trying to return anything here
// simply do something with the response
// Depending on what the server sent you there
// will be different ways.
// Here you could also call some other custom function
// and pass it the response
}
'json'
);
}
You can't return values from ajax calls. (Without setting async false, but that wouldn't really be ajax)
By the time you hit the inner return, the outer function has already completed
You will need to use a callback to process the users.
get_users(function(response) { // this anonymous function is passed in as a parameter
// do something with the response
});
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// call the passed in function and pass in the response as a parameter
callback(response);
},
json'
);
}
You need a primer on how asynchronous ajax calls work.
When you call $.post(), it starts a networking call to do the post and immediately returns from the $.post() call and continues executing the rest of your javascript. It will even exit your function get_users() right away.
But, the ajax call is not yet done - it's still in progress. Some time later, the ajax call will finish and when that happens the success handler for the ajax call that you have defined as function(response) {...} will get called. Only then, at that later time, is the response value from the ajax call known.
This is what asynchronous ajax means. You cannot write a call like get_users() and expect it to get the users and return with them. Instead, you have to make use of callback functions that will get called some time later (when the ajax has completed) and you can continue the path of your code then. Yes, this is inconvenient, but it's how things work in javascript with asynchronous ajax calls. The benefit of asynchronous ajax calls is that the browser and other javascript code can be fully live while the ajax call is underway. The cost of asynchronous ajax calls is that coding for them is more complicated.
You have a number of choices for how to deal with this complication. First off, you can make your get_users() call and then just continue the programming sequence that you want to carry out in the internal callback inside of get_users() since that's the only place that the response (the actual users) is known. If you're only using get_users() in one place in your code, then that could work fine. It would look like this:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
},
'json'
);
}
If you need to use get_users() in several different places for different purposes, then you can change it to take a callback itself and let the post call just call that callback when the ajax call is done. You would then complete your processing of the response in that callback function:
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
callback,
'json'
);
}
In this second option you could call get_users() like this:
get_users(function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
});
There are even more advanced options available using jQuery's deferred object.

JavaScript variable reference problem

I'm trying to send a request and then in callback function, change the parameters and then send the request again. Something like this:
function sendRequest() {
params = {param1:'value', param2:'value'};
while(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
else
params = null;
});
}
}
But params never changes and the while loop continues for ever. It seems to be a reference problem; but I can't figure out how to solve this. Thanks in advance.
The problem is that getJSON is asynchronous.
while(params) executes. It's truthy, so we continue
$.getJSON is called. The function passed to it will not be called at this time. It's just queued to the subsystem that later will perform the actual request - asynchronously.
while(params) executes again. The callback passed to getJSON has not gotten a chance to run yet, so params is unchanged.
Go to step 2.
In other words, you created an infinite loop, since the system that processes the queued callback function never gets to execute because of the infinite loop. All you end up doing is creating a infinitely long list of queued getJSON calls.
A better solution would be something like this:
function sendRequest(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
sendRequest(params);
else
params = null;
// Probably do something like requestChainFinished(params);
});
}
sendRequest({param1:'value', param2:'value'});
By using a function, you take control of the flow and don't perform another request until the asynchronous callback to getJSON has been called.
'params' is a closure variable. The value of params changes at a later time in the callback when the asynchronous ajax call's response arrives, but your while loop is keeping the JS engine busy that the callback isn't going to get called ever.
Either you could keep calling the same function in the response callback or you can use async: false like this $.ajax({ async: false, ...

Categories