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
});
};
Related
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 5 months ago.
I have the below java script function, the global variable description1 is updated in the nested JQuery, But when i try to display the variable or set the result as text for a label, it is not displayed. Kindly advice. Thanks in advance.
<script type="text/javascript">
var description1 = "";
function onSelect(e) {
var item = e.item;
var partcode = item.text();
$.ajax({
url: '#Url.Action("GetDescription", "Orderlist")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': partcode },
success: function (results) {
description1 = results;
},
error: function () {
alert('Error occured');
}
});
alert("DESC: " + description1)
document.getElementById("TechDescription").innerHTML = description1;
}
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 3 years ago.
I'm trying to generate an array from ajax result. When my code runs it populates the list. But once the ajax call is done, and I start iteration of that populated list, it doesn't output anything.
When I put it in debugging mode I can see that the array "tlitems" is getting populated.
But then after last item is added, it goes out.
var tlitems = [];
function GetTL() {
$.ajax({
type: 'GET',
url: '/PTL',
datatype: 'json',
headers: headers
}).done(function(ptl) {
$.each(ptl, function(key, value) {
var pid = this.pid;
var owner = this.strowner;
var dbtstamp = this.db_tstamp;
var tlt = "pi";
item = {}
item["_pid"] = personid;
item["_owner"] = owner;
item["_dbtstamp"] = dbtstamp;
item["_tlt"] = tlt;
tlitems.push(item);
});
}).fail();
$.each(tlitems, function(k, v) {
alert("Key: " + k + ", Value: " + v);
})
};
It should alert with K:V. But it just comes out.
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 5 years ago.
I have function that is used from few different places in the system. All I need now is to return true or false depends if function completed successfully or not. here is example of what I have so far:
function userUnlock(userID){
var fnResult;
$.ajax({
type: 'POST',
url: 'Application.cfc?method=removeLock',
data: {'userID':userID},
dataType: 'json'
}).done(function(obj){
if(obj.STATUS == 200){
fnResult = true;
}else{
fnResult = false;
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
return fnResult;
}
Here is my onClick fucntion:
$("#unlockBtn").on("click", function(){
var userID = $.trim($("#userID").val());
if(userID){
console.log(userUnlock(userID));
$("#unlockBtn").prop("disabled",true);
$('#searchMsg').addClass("success").show().text("User is unlocked.").delay(3000).fadeOut('slow').queue(function(){
$(this).removeClass("success").dequeue();
$("#unlockBtn").css("display","none");
});
}else{
$('#searchMsg').addClass("error").show().text("Error.").delay(3000).fadeOut('slow').queue(function(){
$(this).removeClass("error").dequeue();
});
}
});
In my onClick function console.log() returns undefined. I'm not sure why that's the case since I have return the variable that is Boolean. Also I was wondering if there is a way to prevent multiple requests onClick. For example if user by accident clicked few times. One way is to set button attribute disabled and I'm doing that but I want to make sure that my function prevents multiple requests. if anyone can provide some example that would be great. Thank you.
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to write a JavaScript function that retrieves surname that corresponds to a supplied email address with no success so far. Here's my code:
function getUsername(){
var username;
$(function(){
var dataString = 'email=' + EMAIL_ADDRESS;
$.ajax({
url: 'user_crud_operations.php',
data: dataString,
dataType: 'json',
success: function(data){
U = data[1];
username = data;
}
});
});
return username;
}
I need to use the retrieved username in another function elsewhere. Where am I going wrong?
Asynchronous functions (as used in AJAX) usually do not return values but instead trigger callback functions.
You must restructure your design so that "getUserName()" passes to a callback instead of returning a value. For example:
function getUsername(handler) {
// ...
$.ajax({
// ...
}).done(function(username) {
if (handler && (typeof(handler)==='function')) {
handler(username);
}
});
}
// Sample usage...
getUsername(function(username) {
alert("OK: username=" + username);
});