This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I was trying to return a value after an ajax call in a function and it kept returning undefined.
I looked it up and learned about callbacks.
I am starting to understand the concept, but little confused over handling it the way I want to
The function:
function count_posts(post_type, callback) {
var s_data = {
count_posts: 1,
post_type: post_type
}
$.post("actions.php", s_data, function(data) {
var r = JSON.parse(data);
callback(r);
});
} // EO count_posts
calling it:
count_posts('all', function(count) { console.log(count); }); // 20 ( working )
handling it differently:
console.log(count_posts('all', function(count) { return count; })); // undefined
Goal:
$('#show_count').html(count_posts('all', function(count) { return count; }))
How do I handle a callback in the way that I want to handle it.
The function doesnt return a value.
The callback is called async
try calling it like this:
count_posts('all', function(count) {
$('#show_count').html(count);
});
The point with such callbacks is, that they are somewhat "called from nowhere".. so you will not return it a value to your code. Instead reverse the call order, in your example:
count_posts('all', function(count) { $('#show_count').html(count); });
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have two functions country and location. When the page loads these two functions will run.
I need to get the result value from $.getScript and use it in the function location().
Currently, I am getting undefined. Please check my code.
Any help would be appreciated.
<script>
$(function () {
var result;
function country() {
$.getScript("ajax/country.js", function () {
result = 'data one'; // I need to get this result in location().
});
}
function location() {
console.log(result); // This result should be 'data one'. Currently, I am getting undefined.
}
country();
location();
});
</script>
$.getScript() works asynchronous. Call location in the getScript function.
$(function () {
function country() {
$.getScript("ajax/country.js", function () {
let result = 'data one'; // I need to get this result in location().
location(result);
});
}
function location(result) {
console.log(result); // This result should be 'data one'. Currently, I am getting undefined.
}
country();
});
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.
...
});
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have the following function in javascript:
function checkFunc(msg) {
$.getJSON("myurl.php", {
dtccode: msg
}, function(j) {
return j.boolField;
}); //JSON call
}
And I call it in another function:
function check(msg) {
var ret = checkFunc1(); //some other function
ret = checkFunc2() && ret; //some other function
ret = checkFunc3() && ret; //some other function
ret = checkFunc() && ret;
if (ret) {
//code
}
}
My problem is, that I know the checkFunc should return false, but it returns true. I think this may be a synchronization issue, but I don't know what to do.
Can anyone help?
AJAX is asynchronous. Means that you have to use callback function to get the result. Like so:
function checkFunc(msg, callback) {
$.getJSON("myurl.php", {
dtccode: msg
}, function(j) {
callback(j.boolField);
}); //JSON call
}
and
function check(msg) {
checkFunc(msg, function(result){
alert(result);
});
}
EDIT: Using deferred system:
$.getJSON("myurl.php").done(function(j) {
callback(j.boolField);
});
You can also add fail() to check for possible error. Check the docs: http://api.jquery.com/jquery.getjson/
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);
});