Ajax jsonp data to an array using Jquery [duplicate] - javascript

This question already has answers here:
Use variable outside the success function from an ajax/jquery call
(5 answers)
Closed 7 years ago.
I have created an jsonp request that retrieves data. The only problem is I cant seem to get the data in a array outside my loop:(
var lookbook_data = new Array();
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
}
});
console.log(lookbook_data);
So when I console.log they array inside the look it output the data the way it should. However outside the function it does not. But I did decleare the variable outside so I really dont get why:(
Btw Sorry for messy codebock cant seem to get it right with 4 spaces:(

That ajax call is asynchronous, so you immediatly reach the last line of your code before it can finish.
You could make is synchronous (not recommended) with
async = 'false'
within the ajax call
or do something like this
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
continueHere()
}
});
function continueHere() {
// rest of the code that handles your ajax call
}

var lookbook_data = new Array(),
XHR = $.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp"
});
//anywhere else in your script you can call :
XHR.done(function() {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
console.log(lookbook_data);
});

use this inside your for loop console.log(lookbook_data[i]); inside the success function

use console.log(lookbook_data); inside the success function

Related

Accessing variable outside ajax body [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 ajax request and I want to access an array defined in the ajax body outside its body.I am new to javascript so any help would be appriciated.This is my ajax request
$.ajax({
type:"GET",
url: url ,
success: function(finalresult) {
arr=[]
for(var i=0;i<finalresult.routes[0].geometry.coordinates.length;i++)
{
arr.push(finalresult.routes[0].geometry.coordinates[i])
global_data =arr.push
}
}
});
How can I access array arr outside the ajax body?
You can access it by creating a variable outside the ajax and setting its value inside the success function. Also note you can get its value only after the ajax & its success has finished its execution. For this you can use ajax done. Otherwise it is always going to give an empty array
let arr = [];
$.ajax({
type: "GET",
url: url,
success: function(finalresult) {
for (var i = 0; i < finalresult.routes[0].geometry.coordinates.length; i++) {
arr.push(finalresult.routes[0].geometry.coordinates[i])
global_data = arr.push
}
}
}).done(function() {
console.log(arr)
});

Javascript global variables not updating properly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here?
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value.
async function doAjax() {
return await $.ajax({
type: "GET",
url: "posts_replied_to.txt"
});
}
let lines = await doAjax()
lines = content.split('\n')
console.log(lines)
Try this code using
Async to get the expected result.
Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX.
You can AJAX asyn:false
What does "async: false" do in jQuery.ajax()?
Before your GET response come your second console.log code also execute due to ajax is not async. Change as below,
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
async: false,
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
Try using promise object returned by ajax call.
var lines = new Array();
var promise_obj = $.ajax({
type: "GET",
url: "posts_replied_to.txt"
}).promise();
promise_obj.done(function(response)
{
lines = response.split('\n');
console.log(lines);
// Rest of your logic goes here where you want to use lines.
});

Unable to update parent functions variable from inside $.ajax call

I am trying to push a value that is being returned inside the ajax call to an array outside of the call, but still inside the parent function. It seems that I am not able to access any variable and update it from inside the ajax success statement. Thanks in advance for the help.
var bill = [];
var billDate = [];
$(document).ready(function(){
$.ajax({
url: '../Js/readData.php',
data: "",
dataType: 'json',
success: function(data)
{
//var obj=JSON.parse(data);
var obj=data;
for (var x in obj)
{
bill.push(obj[x].Amount);
billDate.push(obj[x].Dates);
}
}
});
The ajax call is asynchronous so the variables are not updated immediately for availability outside of the success function. It is called after the time involved with loading the data from the server.
You may want to move the anonymous success function to an external function and do whatever handling you need in there.
$(document).ready(function(){
$.ajax({
url: '../Js/readData.php',
data: "",
dataType: 'json',
success: mySuccessFunction
});
var mySuccessFunction = function(obj) {
for (var x in obj)
{
bill.push(obj[x].Amount);
billDate.push(obj[x].Dates);
}
}

Javascript Array Variable Scope [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a problem with array variable scope in Javascript. Here's my code
var features = new Array();
var x = 0;
$.ajax({
async: true,
url: domain + "client/applications/getFeatures",
dataType: 'json',
success: function(data) {
if (data.code == 200) {
$.each(data.data, function(i, val) {
features[x] = val.features_value;
x++;
});
}
}
});
alert(features[0]);
The result of the pop up always "undefine". Do you have solutions ? Thank you
You problem isn't with variable scope, it's with async code.
Your alert is fired before the success callback, so features hasn't been set yet. Do something like this instead:
$.ajax({
// ... other AJAX opts
success: function(data){
var features = new Array();
if(data.code == 200){
var x = 0;
$.each(data.data, function(i, val){
features[x]=val.features_value;
x++;
});
}
alert(features[0]);
}
});
If you need to use the alert(); (eg, you're not using it for debugging) then you'll need to include it within the success function because it's asyncronous and needs to wait until it gets the response before showing the value!

scope of var in jquery function? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does Asynchronous means in Ajax?
why my var "temp" is 0 after the ajax?
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
Because the ajax call is asynchronous, so temp is returned before being updated ...
Because the success function doesn't run until the HTTP response is comes back from the server.
Ajax is asynchronous.
Do what you want to do with the data in the success function (or in functions you call from it).
Don't try to wait for a response and then return data to a calling function.
Ajax calls are asynchronous but you can use CommonJS Promises/A pattern to achieve what you want. jQuery provides it's own implementation of it: jQuery.Deferred().
As others have mentioned here, because ajax is asynchronous, you're not guaranteed to get the updated temp variable before your return statement. It would be best to work within your success function. However, if you absolutely have to wait for that call to finish and return the temp variable, you can make it Non-asynchronous by adding async: false
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
async: false,
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
S.ajax/$.post/$.get etc etc, all these are asynchronous process (which means, you will come out of the loop even before $.ajax is completed, even though it will be going to server side after coming out of the loop)
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
.............
..............
}
});
return temp;
}
So just after the loop if you will check, the following statement might not have executed(depending upon the data set).
temp = parseFloat(myJSONObject.bindings[0].value);
so to check the data in temp variable you should put a debugger/alert inside $.ajax. example :
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
alert(temp);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
now you will get the value of temp

Categories

Resources