This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I spent lot of time to figure this out but did not find anything,
function constructAgenciesData() {
$.ajax({
url: "getAgenciesAndGlobalJson.do",
dataType: "json",
success: function(data){
$.each(data, function (index, row) {
// console.log("data : "+ JSON.stringify(data));
$("#"+row.id).data("assignedAgencies", row.assignedAgencies).data("restOfAgencies", row.restOfAgencies).data("global", row.global).data("globalID", row.globalID);
});
}
});
}
constructAgenciesData();
$(function($){
$(".globalswitch").each(function () {
var idRow = $(this).parents('tr')[0].id;
alert(idRow);
console.log($('#'+idRow).data("global"));// <-- UNDEFINED
$(this).switchButton({
checked: row.data("global")
});
});
$(document).on('click','button.btn', function () {
var idRow = $(this).parents('tr')[0].id;
var title = $(this).parents('td:first').siblings(':eq(1)').text();
title = "Rule Name : " + title;
$("#divPopUp").data('param_1', idRow);
$("#divPopUp").data('opener', this).dialog("option", "title", title).dialog("open");
console.log($('#'+idRow).data("global"));// <-- WORKING
var old_array = $('#'+idRow).data("restOfAgencies");
var new_array = $('#'+idRow).data("assignedAgencies");
addCheckbox(diff(old_array,new_array));
});
});
I don't know why the same line :
console.log($('#'+idRow).data("global"));
is undefined in the .each function.
BUT it is working in the click function .
Your $.ajax call is asynchronous. This means that it is firing request while the rest of the Javascript is being run.
The success function within constructAgenciesData() might not have been completed prior to the IIFE $(function($){.
Therefore, there is no guarantee that the .data('global') will be set by the time you're trying to access it within the $(".globalswitch").each loop.
A solution to this issue would be to wrap the $(".globalswitch").each loop within a function globalSwitchLoop() and fire that on the success of the $.ajax call.
Also, take a look at jQuery's promises.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Context
I have a function that is called within an AJAX call that returns a number. I set this number to a variable and want to access the number outside of the .done() method:
$.ajax({
url: 'urlhere.php',
type: 'GET',
data: {text: text},
success: function(data) {
var getNumber = countNumber();
getNumber.done(function(data) {
var number = data;
});
let newContent =
"The number is "+
number;
}
});
But I get this error, stating that the variable is not defined:
Uncaught ReferenceError: number is not defined
Question
How do I access variables within the .done() method in jQuery in an AJAX call?
Things I Have Tried
I have already tried defining the variable before the function call and then changing it in the done() method, like so:
var number; //initialize variable
$.ajax({
url: 'urlhere.php',
type: 'GET',
data: {text: text},
success: function(data) {
var getNumber = countNumber();
getNumber.done(function(data) {
number = data;
});
let newContent =
"The number is "+
number; //console.log's "undefined"
}
});
This only makes the variable equal to undefined, so I don't think anything inside the done() method is able to change existing variables. Any ideas? Let me know if there is any confusion. Thanks.
It seems getNumber.done() is asyncronous. Which means it takes a while to update the the value of number;
You may do this:
$.ajax({
url: 'urlhere.php',
type: 'GET',
data: {text: text},
success: function(data) {
var getNumber = countNumber();
getNumber.done(function(data) {
number = data;
let newContent = "The number is "+ number; //console.log's "undefined"
});
}
});
Your problem is that the code is asynchronous so the number variable won't be assigned just after you can the done() function.
var getNumber = countNumber();
getNumber.done(function(data) {
number = data;
});
// number won't exist here.
let newContent = "The number is "+ number; //console.log's "undefined"
What you can do:
Use a promise and use resolve on the done() callback. You will need to await after it.
Call a function from .done() callback and keep your process from there
Something like this:
var getNumber = countNumber();
getNumber.done(function(data) {
number = data;
// Your code should flow from here.
yourDoneFunction();
});
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Sorry for the simple question, I am new to Javascript and Ajax.
Here is my code:
var rootURL = "http://localhost:8080/WineCellar/rest/wines";
var findById= function(id){
var testWine;
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: 'json',
success: function(data){
console.log('findById success: '+ data.name);
testWine = data;
}
});
return testWine;
};
var myWine = findById(3);
console.log(myWine.name);
It gives the following console output:
https://i.stack.imgur.com/JqmHQ.png
Cannot read property 'name' of undefined
myWine is undefined. How do I fix this? Is it possible there are two ways of overcoming this problem? Perhaps I need to add a parameter to the ajax method?
Perhaps you could try using the fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) heres an example
let YOUR_API = "https://swapi.dev/api/people/1/";
let cache;
window.onload = function () {
fetch(YOUR_API)
.then((response) => response.json())
.then((myJsonResponse) => {
cache = myJsonResponse;
console.log(cache);
// the rest of the code that runs on this response
});
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an array declared in an else structure
var days = new Array();
$.ajax({
url: 'someurl',
dataType: 'jsonp',
success: processJSON
});
I process the data from the ajax call in the processJSON function
function processJSON(jsonData) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
}
I add some other arrays to the days-array.
If I check it in the console (in the processJSON-function), the length is three/
Then when I want to use the variable in some code under the the ajax-call, nothing works and when I check the length it's 0. I guess it's something with declaration?
Is your code under the Ajax call happening after the processJson function? The call to the ProcessJson function is asynchronous and happens only after the Ajax call finishes. However the code following it might happen before. So it might be a timing thing. If you need the array for any other processing you should have it in the callback or after you know the callback has been finished.
Put the declaration outside of the condition/else
var days = new Array();
if(...){
}else{
$.ajax
}
You need to wait until the XHR call has finished. It looks like you're using JQuery so check out their deferred docs (http://api.jquery.com/deferred.then).
You would end with something like this:
$.ajax({
url: 'someurl',
dataType: 'jsonp'
}).then(function( jsonData ) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
console.log( 'done!', days );
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
I'm trying to get some HTML content via ajax. But for some reason, though the HTML makes it to the ajax function, when I try to use it as a returned value, I get undefined.
Like this:
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
console.log(p); //prints out all the HTML just as I would expect
return p;
});
}
but when I try to get the HTML to append it to my page like this
if (has_additional_options == "t"){
var html_to_append = get_additional_options(name);
console.log(html_to_append); // undefined
}
It is the same result if I use the done() method, or just return the value as a success callback. What is my error?
You can't return values from asynchronously called functions.
You should return post (i.e. the result of $.ajax) and then register a .done handler outside of your function:
function get_additional_options(name) {
return $.ajax({
...
});
};
if (has_additional_options == "t") {
get_additional_options(name).done(function(p) {
console.log(p);
});
// NB: code execution continues here immediately - don't do anything
// else here - all further stuff must be done in the above callback
}
You are returning the HTML value inside the anonymous function.
You're basically passing it to the post.done method.
Maybe it's better to use events in this case since you're running asynchronous code here.
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
$("body").trigger("html_loaded",[p]);
);
}
$("body").on("html_loaded", function (htmlData) {
// Do something with your HTML data here.
$(this).append(htmlData);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I wanted to grab the value on an ajax call using a function. but the value always return as undefined. return value is only 1 or 0.
Here is my code:
$(function(){
$('#add_product').click(function(){
var i = $('#product_name').val();
param = 'product_name='+i;
var value = check_product(param);
alert(value);
return false;
});
});
function check_product(param){
$.ajax({
type : 'POST',
data : param,
url : baseurl+'cart/check_product_name/',
success : function(result){
//alert(result);
return result;
}
});
}
I am still working on getting this one work. I get the value now showing 1 or 0. What im trying to accomplish now is how I can it in the if statement. I wanted to have something like this. If val = 0 return true; else return false. Im not sure I'm in the right track of using the ajax function. But if there a better way you can show me I will appreciate it.
$(function(){
$('#add_product').click(function(){
var i = $('#product_name').val();
param = 'product_name='+i;
check_product(param).done(function(value) {
var val = value; //waits until ajax is completed
});
if(val == 0){
return true;
} else{
return false;
}
});
});
function check_product(param){
return $.ajax({
type : 'POST',
data : param,
url : baseurl+'cart/check_product_name/'
});
}
It's asynchronous, so you have to wait for the ajax call to get the data back before you can alert it. You can do that easily by returning the ajax call and using done(), like so:
$(function() {
$('#add_product').click(function() {
var i = $('#product_name').val(),
par = 'product_name=' + i;
check_product(par).done(function(value) {
alert(value); //waits until ajax is completed
});
return false;
});
});
function check_product(param) {
return $.ajax({
type : 'POST',
data : param,
url : baseurl + 'cart/check_product_name/'
});
}
Add this to ajax options:
dataType: "json",
and use
return Json(dataObject, JsonRequestBehavior.AllowGet);
in your action method.
Your
return result;
in the success handler of ajax is not a return for check_product. Pass another function (possibly anonymous) to check_product and call on ajax success.