Global variable which is updated in nested JQuery is not displayed [duplicate] - javascript

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;
}

Related

Ajax method, undefined variable, two possible solutions? [duplicate]

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
});
};

After pushing to an array from an ajax call, getting array element by index shows undefined, but console show array content [duplicate]

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 an ajax call when my page loads, the result is a integer number that I need to save in a variable to use later with other jquery functions.
This is my code right now
$(document).ready(function() {
var ajaxResult = new Array();
$.ajax({
url: '<?php echo base_url(); ?>index.php/Po_general/obtenerIdConsecutivo',
method: 'GET',
success: function (returned) {
var returned = JSON.parse(returned);
var idPog = returned.idPog;
ajaxResult.push(idPog);
}
});
//This shows me the array in the console
console.log(ajaxResult);
//This shows undefined
console.log(ajaxResult[0]);
/*
* Additional jquery functions
*/
});
console.log(ajaxResult) shows me the array in the console
[]
0: 2
length: 1
But when I want to access ajaxResult[0] it shows as undefined.
Can you try with this -
$(document).ready(function() {
var ajaxResult = [];
$.ajax({
url: '<?php echo base_url(); ?>index.php/Po_general/obtenerIdConsecutivo',
method: 'GET',
success: function (returned) {
var returned = JSON.parse(returned);
var idPog = returned.idPog;
ajaxResult.push(idPog);
}
});
//This shows me the array in the console
console.log(ajaxResult);
//This shows undefined
console.log(ajaxResult[0]);
/*
* Additional jquery functions
*/
});

javascript pass array data with push, outside ajax success call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I want to read the (images) files name inside a specific folder and then to preview images in Krajee Bootstrap FileInput (FileInput demo link) .
I have a problem with this code in javascript:
var initialPreviewArray = [];
var j = [];
$.ajax({
type: "POST",
url: "my_gallery_ajax.php?",
async: "FALSE",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert('ok');
$.each(data, function(i,filename) {
j[i] = filename;
initialPreviewArray.push("<img id='"+i+"' src='user_1/'"+j[i]+"'>");
});
alert(j[2]); // test - is working - value: '11.jpg'
}
});
alert(j[2]); // test - not working - value: 'undefined'
My goal is to fill 'initialPreviewArray' with data from AJAX, inside or outside.
Inside 'AJAX call' initialPreviewArray.push is not working, even with specific value (outside AJAX is working):
initialPreviewArray.push("<img style='height: 50px' id='1' src='user_1/1.jpg'>");
Conclusion: I am not able to get data outside AJAX.

Store a Javascript variable in next variable statement [duplicate]

This question already has an answer here:
Jquery:How to use variable as a selector
(1 answer)
Closed 9 years ago.
I have this code
<script type = "text/javascript">
$(document).ready(function(){
$(".sub_category").click(function()
{
var main_cat = $("input[name='category_form_cat_1']:checked").val();
var sub_cat_form1 = $("input[name='subcategory_form_cat_1']:checked").val();
$("input[name='subcategory_form_cat_1'][value=sub_cat_form1]").attr("checked",true);​
$.ajax
({
data: {'cat':main_cat,'sub_cat':sub_cat_form1},
url: "ajax_files/events-select.php",
type: 'GET',
success: function(data)
{
$("#displayedresults").html(data);
$('#loading_spinner').hide();
$('#loading_text').hide();
$('#loading_row').hide();
$('#displayedresults').show();
//$('.button_export').show();
//$("a.button_export").attr("href", string);
}
});
return false;
});
});
I need to store this line value in the next one
var sub_cat_form1 = $("input[name='subcategory_form_cat_1']:checked").val();
$("input[name='subcategory_form_cat_1'][value=sub_cat_form1]").attr("checked",true);​
you can do it like this
var sub_cat_form1 = $("input[name='subcategory_form_cat_1']:checked").val();
$("input[value="+sub_cat_form1 +"]").attr("checked",true);​

Javascript retrieving username from db [duplicate]

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);
});

Categories