AJAX functions returning values [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have the following function but I can't seem to get returnedData = result to successfully set the value. If I include alert(result) in the same location, the popup displays the string I'm looking for correctly.
Is there something I'm missing here? I had thought because I declared the variable returnedData outside the function it would be accessible everywhere?
function AJAXprocesstwoVariables(Var1, Var2) {
var V1 = Var1,
V2 = Var2;
var returnedData;
$.post(
processinglocation, {
data1: V1,
data2: V2
},
function (result) {
returnedData = result; // *<- this doesn't work*
// alert(result); // *<-this works*
}
);
return returnedData;
}
var ReturnedInfo = AJAXprocesstwoVariables(Var1, Var2);
$('body').append(ReturnedInfo);

$.post will run asynchronously. Once that line is run, the request will be made in the background, and you will immediately hit the return line of AJAXprocesstwoVariables. You are attempting to use returnedData before it is set in the success function of your $.post.

Related

How to return a value after ajax call? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I want to return a ajax call value to other function. Code shown below
script
var obj2 = ajax_call();
function ajax_call() {
var obj3;
$.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
obj3 = $.parseJSON(data);
});
return(obj3);
}
console.log(obj2+'test');
function ajax_call() {
return $.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
return data;
});
}
var obj2 = ajax_call();
console.log(obj2+'test');
AJAX returns result in future (that's why it is asynchronous). Since JavaScript runs in a single thread, you cannot return a value immediately.
You need to understand jQuery's Promise API instead, which $.post already supports.
Modify your code a bit to leverage the power of promises in your code.
function ajax_call() {
return $.post("action.php", {action: 'view_style_code_action',style_val: v})
}
ajax_call()
.then(function(data) {
// Do the parsing here
var obj3 = $.parseJSON(data);
// Do rest of your work here.
...
});

How I can return a string from a javascript callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.

Trouble returning value of nested function using an ajax call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to append the results from an ajax call to a paragraph using jQuery.
I would like to return the variable "myResult" from the inner getResult function and pass it to the outer buildParagraph function, but the value returned is undefined.
How do I append the value of myResults to the <p> tag as indicated below?
function buildParagraph () {
function getResult(url) {
$.getJSON(url, function(data) {
var myResult = data.results;
return myResult;
}
}
var myUrl = 'www.mywebsite.com';
getResult(myUrl);
$('<p>').html(myResult);
}
You need to have a callback function inside ajax success,Or the easiest way is move the below code to the ajax success function
$('<p>').html(data.results);

Javascript: Accessing external variable within anonymous function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
See the following JavaScript:
(function() {
var allMatches = [];
$.getJSON("myURL", function(data) {
$.grep(data.feed.entry, function(element, index) {
var match = {
day: element.gsx$day.$t,
winner: element.gsx$winner.$t,
field: element.gsx$field.$t,
time: element.gsx$time.$t,
grade: element.gsx$grade.$t,
round: element.gsx$round.$t,
teamOne: element.gsx$team1.$t,
teamOneGoals: element.gsx$goals.$t,
teamOnePoints: element.gsx$points.$t,
teamOneTotal: element.gsx$totalscore.$t,
teamTwo: element.gsx$team2.$t,
teamTwoGoals: element.gsx$goals_2.$t,
teamTwoPoints: element.gsx$points_2.$t,
teamTwoTotal: element.gsx$total.$t
}
allMatches[index] = match;
});
});
var fridayMatches = SQLike.q(
{
Select: ['*'],
From: allMatches,
Where: function(){return this.day === "Friday"},
OrderBy: ['field','|asc|']
}
);
console.log(fridayMatches);
})();
If I put a breakpoint at allMatches[index] = match; I can clearly see this array being populated fully
However, if I put a breakpoint further down at the start of my SQLike code allMatches is completely empty.
Why is this, and what is the solution?
Becouse $.getJSON is asynchronous.
You have to put your SQlite code in a function and call it from the $.getJSON callback.
$.getJSON is does an Ajax call and the "a" in Ajax standards for asynchronous.
The anonymous function that you use to handle the ajax response won't run until the ajax call is returned.

js function inside function and wait for return value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
$(document).ready(function(){
// Global function (will be include in any HTML file)
function m3_result(size_1, size_2, size_3){
$.get('http://www.google.com', function(data){
return data;
});
}
// Another function
function calculate(){
var size_1 = parseFloat($('#add_document_form #size_1').val());
var size_2 = parseFloat($('#add_document_form #size_2').val());
var size_3 = parseFloat($('#add_document_form #size_3').val());
var ax = m3_result(size_1, size_2, size_3);
alert(ax); // Here ax return: UNDEFINED
}
// Run
calculate();
});
Results are "undefined", but I would like that calculate() will wait for m3_result() to execute. I see that here problem is coming when I added $.get(), but its needed...
I have searching for callback() like functions, but none fit to my needs, or I just didnt put that right.
Any help will be highly appreciated, thanks.
GET url will be localy and element IDs are also ok.
You can't return a result from an asynchronous function, instead you can return a promise to supply that value later, which as it happens is the jqXHR object returned by $.get:
function m3_result() {
return $.get(...)
}
and do the same in calculate:
function calculate() {
...
return m3_result(...);
}
and then wait for the result, which will be passed as a parameter to the callback registered with the .done function:
calculate().done(function(result) {
alert(result);
});

Categories