Extracting Array - undefined [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have an ajax getting values from db, and the result is pushed into an array:
function pushPONFail(dt, ct) {
if (ct < 12) {
var tMon = parseInt(dt.getMonth())+1;
var tYear = dt.getFullYear();
ct++;
} else {
return;
}
data = {"qType": 101,
"tbl": 'qualitypqa.dbo.centerthickness',
"month": tMon,
"year": tYear,
"type": 'Lotrafilcon B'};
$.ajax({
cache : false,
url: "getrpt.php",
type: "get",
data: data,
contentType: 'application/json; charset=utf-8',
async: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error: "+textStatus+" : "+errorThrown);
}
})
.done(function(response){
var obj = jQuery.parseJSON(JSON.stringify(response));
arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail});
dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1));
pushPONFail(dt, ct);
});
} // pushing values such as ["May/2017", 0]
$(function() {
var dt = new Date();
pushPONFail(dt, 0);
console.log(arrPONFail);
});
These are the complete function. When I console.log the array, it came out as my picture. I'm unable to extract the data.
When I print the array into the console, it came out as the picture below.
How do I get the values back out from the array?
When I do an arrT[0], I get an undefined.
Please advise.

This is most likely an asynchronous issue - are you accessing arrT[0] outside of the .done() function? If so, at the time you're accessing it, there is nothing in the array - it's empty. The ajax request you're making takes some time (milliseconds), and only after that data returns does your array have something in it. To use the values in the array, try putting the code that uses the array inside the .done() function itself.

Related

how to properly use else if in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have this script for submitting a form using jquery ajax, everything works fine except i can only get two responses, the loading part is implemented but the rest of them i can only get the else statement. the else if, none is working.
the json statement works just fine. and the data is passed to php successfully but the responses are not according.
(function($) {
'use strict';
const FormFunction = function(){
const checkSelectorExistence = function(selectorName) {
if(jQuery(selectorName).length > 0){return true;}else{return false;}
};
let registerForm = function() {
if(!checkSelectorExistence('.registration-form')){return;}
jQuery('.registration-form').on('submit', function( event ) {
event.preventDefault();
let response = $('.loading').addClass('show').show();
jQuery(this).find(".message").addClass('active').show('slow');
const formData = new FormData(this);
const formAction = jQuery(this).attr('action');
jQuery.ajax({
type: 'POST',
url: formAction,
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
beforeSend : function(){
$('.info').addClass('show').show('slow');
},
complete : function(){
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
success : function(data)
{
if(data.status === 1){
response = $('.success').addClass('show').show('slow');
}
else if(data.status === 2) {
response = $('.taken').addClass('show').show('slow');
}
else if(data.status === 0){
response = $('.empty').addClass('show').show('slow');
}
else {
response = $('.error').addClass('show').show('slow');
}
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
error : function(data){
$('.error').addClass('show').show('slow');
$('.registration-form')[0].reset();
},
});
});
}
/* Functions Calling */
return {
afterLoadThePage:function(){
registerForm();
},
}
}(jQuery);
/* jQuery Window Load */
jQuery(window).on("load", function (e) {FormFunction.afterLoadThePage();});
})(jQuery);
Based on some comments that we traded I managed to test it out and found out, what is the root of your problem. Even thought you are setting dataType as JSON, what you actually pass from PHP is a string of value "{\"status\":1}". This is currently the content of your data variable in Success function of your AJAX call.
Adding following line of code at begging of your Success function will do what you want it to do: data = JSON.parse(data);. This will parse string returned by PHP into an JSON object in JS which will create data.status instance holding desired value of number type.
I did some test on my end and it worked as expected with IF and ELSE IF as well.

Accessing an Array returned by a function in JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I've got the following code:
$(document).ready(function() {
var blu = getData();
console.log(blu); //this shows full the array in the console
console.log(blu.length); //this gives back 0
});
With the following function getData()
function getData() {
var arr = [];
var json;
$.ajax({
url: "someurl.com",
dataType: 'json',
data: json,
success: function(json) {
var x = json.somejson.somenumericvalue //gets the amount of dataentries
for (i = 0; i <= x - 1; i++) {
arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
}
} //end of success function
}); //end of ajax
console.log(arr.length) //shows the correct length of the array
return arr;
} //end of function getData
Problem is I want to access the values and do methods (like .length) with the array which is filled in the function but it somehow does not work. Anyone can help out?
Cheers.
You can use $.each or for in loop
E.g.
$.each(Blu, function (i, v){//do whatever with array values, i: index, v: value}
Or
For(i in Blu){//i: index, access your value by Blu[I] & do whatever with your value}
Hope it'll help you out
The json data returned by the ajax call must be accessed by object notation if it is a named array. To retrieve the length of such an data object use:
Object.keys(data.datanode).length
It is not clear what your json looks like, you probably need to iterate through it. Assuming that you want to iterate through json.feeds:
function getData(){
var arr = [];
var json;
$.ajax({
url: "someurl.com",
dataType: 'json',
data: json,
success: function(json){
for(var i in json.feeds) {
arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
}
console.log(arr.length)//shows the correct length of the array
return arr;
} //end of success function
}); //end of ajax
}//end of function getData
Also note where console.log and return is. I would suggest reading a basic book about javascript, specifically closures and variable scope. That's why your code doesn't work and the problem is not in ajax, json, or object iterating.

JSON to ver strage cache issue [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 6 years ago.
Im retriving data from my php and its working fine , the problem is that
var myData is getting cached and only updates if i refesh my page 2 times...
on my firebug i can see the post updates but when i `console.log(myData);the data is the old one ..until i refresh..
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
}
});
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
You're probably trying to set and read mydata before the request/response is complete. Instead, move that into your success callback.
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
}
});

Why return not working after Ajax call jquery? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am not able get the returned value after ajax call. I can see that values are being returned but when I do console.log() it shows undefined. Is there something wrong in my approach.
var base_path = "http://localhost/lab/theapp/api/"
$(function () {
var url = base_path + "tasks"
var type = "post"
var data = ""
var get = submit_me(type, data, url)
console.log(get)
})
function submit_me(type, data, url) {
try {
$.ajax({
url: url,
type: type,
data: data,
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", $.cookie("token"))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('page_login_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest))
console.log(JSON.stringify(textStatus))
console.log(JSON.stringify(errorThrown))
},
success: function (r) {
if (r.sessid) {
var sessid = r.sessid
var session_name = r.session_name
var token = r.token
jQuery.cookie("token", token)
return r
}
},
})
} catch (error) {
console.log(error)
}
}
Your ajax call will take some time to retrieve that values. You cannot pass the value directly to the variable. Write the code in ajax success function. ie console.log() in ajax request function. That would follow the delay caused by the ajax call. Try this link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings Check the async attribute here and experiment.

Array doesn't keep content, maybe something with declaration [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an array declared in an else structure
var days = new Array();
$.ajax({
url: 'someurl',
dataType: 'jsonp',
success: processJSON
});
I process the data from the ajax call in the processJSON function
function processJSON(jsonData) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
}
I add some other arrays to the days-array.
If I check it in the console (in the processJSON-function), the length is three/
Then when I want to use the variable in some code under the the ajax-call, nothing works and when I check the length it's 0. I guess it's something with declaration?
Is your code under the Ajax call happening after the processJson function? The call to the ProcessJson function is asynchronous and happens only after the Ajax call finishes. However the code following it might happen before. So it might be a timing thing. If you need the array for any other processing you should have it in the callback or after you know the callback has been finished.
Put the declaration outside of the condition/else
var days = new Array();
if(...){
}else{
$.ajax
}
You need to wait until the XHR call has finished. It looks like you're using JQuery so check out their deferred docs (http://api.jquery.com/deferred.then).
You would end with something like this:
$.ajax({
url: 'someurl',
dataType: 'jsonp'
}).then(function( jsonData ) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
console.log( 'done!', days );
});

Categories