How can I iterate through an array of object in jquery.? [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 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.

Related

Global variable which is updated in nested JQuery is not displayed [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 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;
}

Ajax multiple ajax request from online file [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 12 months ago.
function addIDS() {
const imdbIDs = [];
imdbIDs.push("id1");
imdbIDs.push("id2");
...
return imdbIDs ;
}
function getThemoviedbIDs(IDs) {
let arr = [];
let urls = [];
for(let i = 0; i < IDs.length; i++) {
urls.push(`...${imdb_ids[i]}...`);
}
$.each(urls, (i, u) => {
$(function() {
$.ajax({
url: u,
dataType: 'json',
success: function(data) {
arr.push(data.tv_results[0].id);
},
statusCode: {
404: function() {
alert('Err');
}
}
});
});
});
return arr;
}
function getDetails(themoviedbID) {
console.log(themoviedbID);
console.log(`...${themoviedbID[0]}`);
}
const imdbIDs = addIDS();
console.log("IMDB IDs: ", imdbIDs);
const themoviedbIDs = getThemoviedbIDs(imdbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
const themoviedbIDs = getThemoviedbIDs(themoviedbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
I am using themoviedb database.
populate() I add imdb IDs to the imdbIDs array, then I get themoviedb IDs by getThemoviedbIDs() function.
In the getDetails() function I would like to make ajax request just like in the getThemoviedbIDs() function, but unfortunatelly there is a problem in there. console.log(themoviedbID) output the appropriate array, but console.log(...${themoviedbID[0]}) output .../undefined...
I can get enough information about the series if I am using themoviedb ID.

How do I fix this error I am reciving in my weather api, 404? [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 12 months ago.
I have this code that uses thezipcodes.net to get latitude and longitude and then it puts it through api.weather.gov to get the weather. The problem is that it is screwing up in the area where it gets the points in the weather.gov API.
In getweatherforecaststuff() it returns a 404 error and is trying to set the ending to 0,0.
let lat = 0;
let long = 0;
let forecaststring = "";
function getLat(zipcode) {
//add code here to get from api
$.getJSON("https://thezipcodes.com/api/v1/search?zipCode=" + zipcode + "&countryCode=US&apiKey=01f2f327b789845bddf7d617257d8f76", function(data) {
lat = data["location"][0]["latitude"];
long = data["location"][0]["longitude"];
});
}
function getWeatherForecastStuff() {
$.getJSON("https://api.weather.gov/points/" + lat + "," + long + "", function(data) {
forecaststring = data["properties"]["forecast"];
});
}
function printStuff(forecaststrings) {
$.getJSON(forecaststrings, function(data) {
console.log(data);
});
}
function getInfoNeeded() {
zipcode = window.prompt("What is your zipcode?");
getLat(parseInt(zipcode));
getWeatherForecastStuff()
printStuff(forecaststring)
}

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

Categories