Can't access global variable in $.ajax.done() [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I'm trying to print through innerHTML some data got with the ajax call, but the global array elements it is not accesible in the done() promise.It is indeed undefined.
Why does that happen?
<html>
<head></head>
<body>
<script src ="jquery.min.js"></script>
<script>
$(document).ready(function(){
var elements = document.getElementsByClassName("wind");
for(i=0;i<elements.length;i=i+1){
$.ajax({
type:"GET",
url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
dataType: "json"
}).done(function(data){
elements[i].innerHTML = data.wind.speed; //elements[i] is undefined
});
//elements[i].innerHTML here elements[i] is OK but I don't have access to "data"
}
});
</script>
<div class="wind">Venice,it</div>
<div class="wind">Rome,it</div>
</body>

Try using the success setting rather than done. This will activate when the request is successful and it returns the data.
$.ajax({
type:"GET",
url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
dataType: "json",
success: (function(data){
elements[i].innerHTML = data.wind.speed;
}),
});

Related

Console displaying different array descriptions for AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have an array which contains objects, which contains an array, which contains objects. It's a little messy, but this is just the way the Google Books API returns information.
var myList = [
{kind:'book', totalItems:1, items: [{volumeInfo:{authors:['JRR Tolkien']},publishedDate:"1965",pageCount:355}]},
{kind:'book', totalItems:1, items: [{volumeInfo:{authors:['HP Lovecraft']},publishedDate:"1930",pageCount:269}]},
{kind:'book', totalItems:1, items: [{volumeInfo:{authors:['Oscar Wilde']},publishedDate:"1920",pageCount:400}]},
];
console.log(myList);
console.log(myList[1].items[0].pageCount);
I can access everything in here with no problems. When I create an identical array, except using an ajax call in jQuery, I can't access any of the objects or array items.
var bookList = $(".book").map(function () {
return this.id;
}).get();
console.log(bookList);
var thelink = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
var allresults = [];
for (var i = 0; i < bookList.length; i++) {
$.ajax({
url: thelink + bookList[i],
dataType: 'json',
type: 'get',
cache: true,
success: function (data) {
allresults.push(data);
}
});
};
console.log(allresults[1].items[0].pageCount);
<!doctype html>
<html>
<head>
<title>Google Books</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Input</h1>
<div id="book-container">
<div id="0618249060" class="book"></div>
<div id="9780743258074" class="book"></div>
<div id="9780345466457" class="book"></div>
</div>
<h1>Result</h1>
<div id="resultContainer">
<!--Put a bunch of stuff here-->
</div>
</body>
</html>
As I understand these should be accessible in the exact same way. My only clue is that in the console the variables 'myList' and 'allresults' show up slightly differently. The second one being accessible, the first not.
I'm very confused and have idea what to search to find a solution! What on earth am I doing wrong? Thank you!
This is because ajax calls are asynchronous. So when for loop is finished, you have a console statement which is being executed but until that time, the ajax calls are not finished and hence you cannot access data correctly. Either you should pass a callback and in that callback you should have console or use axios js( promise based HTTP library)
move the line console.log(allresults[1].items[0].pageCount); inside the success callback. It didn't work because ajax is asynchronous and because of that your console.log is diplayed before the ajax call is finish.
your code should be something like:
var thelink = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
var allresults = [];
for (var i = 0; i < bookList.length; i++) {
$.ajax({
url: thelink + bookList[i],
dataType: 'json',
type: 'get',
cache: true,
success: function (data) {
allresults.push(data);
// check if it's the last result, if so check all the values inside allresult
}
});
};

How to pass a JS value into a PHP parameter [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
In the code added here, I pass on value from PHP parameter to JS parameter:
Both parameters are called 'stv'.
I wonder how do I do the exact opposite?
Thanks!
<script>
var stv="<?php echo $stv; ?>";
</script>
send a request with ajax using jquery if using jquery already in document.
If you don't have Jquery added, you can add it ath the end of your html body using a script tag and getting the download adress from google:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
function ajax(value) {
var x = {
'info': value //data to send can be json or something else
};
$.ajax({
url: 'index.php', //page where to send
type: 'POST', //type of request
data: x, // data to send
success: function(data) { //what happends when request is success
try {
getAjPromise(JSON.parse(data));
} catch (e) {
console.log("error");
}
}
});
}
in PHP you check if there is a $_POST['info'], get the value and do something

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

Explination of Javascript function(return value&input parameter related)

<script type="text/javascript">
function pala(data) {
$("#pala").html(data.level);
}
$(document).ready(
function(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/ragnaros/sanral?fields=talents&jsonp=pala",
type: 'GET',
dataType: 'jsonp'
});
});
</script>
In my eyes the function pala is closed on 4 line in the javascript but for some reason it continues(?).
Anyone that can simply how I read this sort of javascript cant wrap my head around it.
Function pala is effectively just doing one thing ($("#pala").html(data.level);). The rest of the code runs because $(document).ready(function) executes the function when the body is loaded.
Here is your code with correct indentation (easier to understand).
function pala(data) {
$("#pala").html(data.level);
}
// Code below runs once when the page is ready.
$(document).ready(
function(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/ragnaros/sanral?fields=talents&jsonp=pala",
type: 'GET',
dataType: 'jsonp'
});
}
);

Looping through the URL in an AJAX call in jquery

So I recently asked a question concerning looping through data in a json file from an asynchronous AJAX call in jquery that uses callback functions (Looping through AJAX and callbacks in jquery) and I got a lot of good help, but now I wonder if I were to have 3 different json files (same structure and naming convention, but holding slightly different data) and their URLs in an array called myURL, would there be a way to loop through the AJAX call for all three URLs and output each of their respective results on a webpage? Below is my code:
<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<script Language="JavaScript">
//New Array for my URLs
var myURL = ["ticker1.json","ticker2.json","ticker3.json"];
function hmm(callback) {
$.ajax({
url : myURL[j], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}
hmm(function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
</script>
</body>
</html>
$.each(myURL,function(i,url){
hmm(url,function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
document.write('<br>');
});
});
});
And in your function -
function hmm(url,callback) {
$.ajax({
url : url,
dataType: 'json',
success: function(response){
callback(response);
}
});
}
Try this
for(var k=0,len=myURL.length; k<len; k++)
$.ajax({
url : myURL[k++], //<<<---Want to loop through this array
dataType: 'json',
success: function(response){
callback(response);
}
});
}

Categories