Scope variable in ajax call - javascript

Why the final console log is undefined?Variable time has a global scope and ajax call is async.
This is my code:
var time;
$.ajax({
async:"false",
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function(data) {
console.log(data);
time=data;
},
error: function(data) {
console.log("ko");
}
});
console.log(time);

Change async to the boolean false.
http://api.jquery.com/jQuery.ajax/
var time;
$.ajax({
async: false,
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data);
time = data;
},
error: function (data) {
console.log("ko");
}
});
console.log(time);
Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.
var time;
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
time = data;
},
error: function (data) {
console.log("ko");
}
})
.then(function(){ // use a promise to make sure we synchronize off the jsonp
console.log(time);
});
See an example like this here using Q.js:
DEMO

In your code, you initialize the global variable 'time' as 'data'. Where does this data variable come from? If the data variable is not global also, when you try to use console.log(time); , it may be undefined because the data variable is undefined.
Make sure both variables are within scope to be used globally. That might work. Good luck!

OK, a bit contrived, but I hope it shows the point regarding scope of time and timing ...
$.ajax({
async: false,
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data.dateString);
time = data.dateString;
},
error: function (data) {
console.log("ko");
}
});
window.setTimeout("console.log('time: '+time)",3000);
JSfiddle

Related

Ending setInterval when ajax call is complete

$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval();
},
succes: function(data){
..................
}
})
So I am trying to end the infinite loop my code is spawning as soon as my ajax call is being done. It now phones pretty much every second to my file to get results, which i want to stop as soon as my ajax call is completed.
I am not sure how to approach this, since if i assign a variable to the setInterval (being it in the function of the beforeSend itself, or outside of the AJAX call), it either wont see the variable, or my variable is empty. I think I am approaching this wrong. Can I check within the beforeSend if the AJAX call is complete to end the loop?
you can store your interval as a global variable and clear it when you need it. like so:
let interval;
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
interval = setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval(interval);
},
succes: function(data){
..................
}
}

Getting Data from Ajax request displayed

I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});

Accessing variable from callback using AJAX in jQuery

Code explains all:
//
// … code ...
//
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
var my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
How do I get access to my_data outside of the AJAX call? I've read that maybe a closure is needed? I can't find any examples that do want I want though.
Many thanks.
Ajax is async call and success may be fired after console.log, you can call a function from success and pass data to it.
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
yourFun(data);
}
});
function yourFun(data)
{
}
To giving function instead of success.
$.ajax({
dataType: "json",
url: "foo",
success: yourFun
});
function yourFun(data)
{
}
Generally speaking, you don't. AJAX calls are asynchronous so there's no guarantee of a value immediately after the jQuery.ajax() function has executed; you need to wait until the AJAX call has completed, and the success callback has executed, before you attempt to use that variable.
The easiest approach is to just use that value inside the success callback. If you really need it to be available outside then make it a variable that's visible to all of your code (not necessarily global, depending on how your code is structured), and check that it has a value before you attempt to use it in any other functions.
Define my_data as global as below,
var my_data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
Declare my_data variable globally..
var my_data = data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
Use my_data as gloabl variable to access data outside of ajax.
var my_data = '';
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
console.log(my_data);

How to check ajax return value

I have an ajax call and it retunrs some value. Now i need to check the value in javascript. How can i do it
$('#cm').blur(function () {
var cmnumber = document.forms['myform']['cm'].value;
$.ajax({
type: 'get',
url: "/validatecm/" + cmnumber,
cache: false,
asyn: false,
data: cmnumber,
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
})
});
Now i need to access the "data" in my javascript submitformfunction. Any help wil be appreciated
success: function(data) {
console.log(data);
useInAnotherFunction(data);
}
function useInAnotherFunction(data)
{
...use here
}
If you use console.log(data); you can view clearly data what you have
You are already accessing the data here
alert(data)
If you still want to access it outside your success callback then make it like this
success: function(data) {
YourFunctionCall(data)
}

ajax call doesnt return the data from external JS file

I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.

Categories

Resources