Adding to my list array from my JSON object - javascript

This is what I am currently doing. I tried just pushing the values from my json into the links array, but upon entering the array the values become undefined. What is a better way to move the data and have it still be usable??
var links = [];
$.ajax({
url: 'data.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.emails).each(function(index, value) {
links.push(value);
});
}
});
//data.json contains:
{
"emails": [{
"source": "1.11913372.-2#multexinvestornetwork.com",
"target": "pallen#enron.com"
}]
}
result from using this code is the same. The values enter the array, but when you access them via links.(name of value) it returns 'undefined'
$.each(data.emails, function(index, value) {
links.push(value);
console.log(links);
return value;
});
Result

Try This
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
//alert("data");
var links = [];
$.ajax({
url: 'test1.php',
type: 'post',
dataType: 'json',
data: {
}
}).done(function(data) {
$.each(data.emails, function(index, value) {
links.push(value);
console.log(links);
return value;
});
});
function getVal(){
console.log(links[0].target);
}
</script>
<button onclick="getVal()">Get target</button>

I think your success callback code is wrong,
the correct way to loop data.emails is,
success: function(data) {
$.each(data.emails, function(index, value) { // <--- change this
links.push(value);
console.log(links); //<--- updated
return value;
});
}

You're calling console.log on a key that doesn't exist. Modify your code to call and print out the array, not a random property.
var links = [];
$.ajax({
url: 'data.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.emails).each(function(index, value) {
links.push(value);
console.log(links);
return value;
});
}
});

Related

Javascript - why is this undefined?

The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.

How do i split ajax return values using jquery

I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},

Using JSON.stringify and can't access the JSON array

I am using php and using json_encode() function I returned/echoed JSON array. I was using jquery ajax and successfully retrieved this data:
[{"id":"1132","city":"Manila Central Post Office","province":"Manila"}]
I use this code on my Javascript btw:
var val = jQuery.parseJSON(JSON.stringify(result));
and when I tried to accessed the data on the array like:
console.info(val.city); // results to undefine
It gives me 'undefined' result. I tried doing For in loop still doesn't work. Maybe I'm doing something wrong, any help would be great. THANKS
Ajax code:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
success: function (result) {
var val = jQuery.parseJSON(JSON.stringify(result, false, replacer));
var val2 = jQuery.parseJSON(val);
console.info(val2);
console.info(val2.id);
},
error: function (e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
val is an array. You need to specify index like below.
var result = [{ "id": "1132", "city": "Manila Central Post Office", "province": "Manila" }];
var val = jQuery.parseJSON(JSON.stringify(result));
alert(val[0].city);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here val is an array of objects, so you cannot access the city value directly by calling val.city. If the data being returned is already encoded by using json_encode(), then you simply need to use $.parseJSON(data). The following code snippet shows how to do this-
var temp = '[{"id":"1132","city": "Manila Central Post Office", "province":"Manila"},{"id":"1133","city": "Another Test Post Office", "province":"Test"}]'; //Defined temp as string since the data response returned from the server should also be a json encoded string.
var val = $.parseJSON(temp);
$.each(val, function(index, item) {
var city = item.city;
$('.container').append('City: '+city+'<br/>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container"></div>
See, the issue can be easily resolved by dataType:"json". If you don't have this attached in your ajax code then the returned response will be a json string and in this case only you have to parse it with jQuery.parseJSON() or JSON.parse().
So, you can add the dataType to the ajax or instead just only parse it.
success: function(result){
var val = jQuery.parseJSON(result); // or JSON.parse(result);
console.info(val[0].city);
},
With dataType:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: 'json', //<-----add this here
success: function(result) {
for (o in result) { // <----and just use this way
console.info(o.city);
}
},
error: function(e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
You don't have to stringify it then parse it to JSON again. You can just add dataType: "json" in your AJAX.
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: "json",
success: function (result) {
console.info(result);
console.info(result.id);
},
error: function (e) {
$("#sys_msg").html(JSON.stringify(e));
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});

How to add each jquery array values inside the single quotes

I have a array in jquery.Now as per my need i have to add each array values into single quotes as ..
var toc='INCOMING','INETCALL','ISD','LOCAL','STD'
But at present i have values like this ..
var toc=INCOMING,INETCALL,ISD,LOCAL,STD
And here is my codes ..
$.ajax({
type: 'GET',
url: 'getdata',
async:false,
dataType: "text",
success: function(data) {
var values = [];
values = data;
values=values.replace('[','');
values=values.replace(']','');
var array = values.split(",");
for(var i=0,len=array.length;i<len;i++)
{
if($.isNumeric(array[i]))
{
callcost.push(array[i]);
}
else
{
toc.push(array[i]);
}
}
alert(toc);
alert(callcost);
}
});
not sure if i got your question right but i guess you are messing up with all this replace/split/... logic. If the data object is an array just try this
$.ajax({
type: 'GET',
url: 'getdata',
async:false,
dataType: "text",
success: function(data) {
var array = JSON.parse(data);
$.each(array, function(i, val){
if($.isNumeric(val)) {
callcost.push(val);
}else{
toc.push(val);
}
});
}
});

looping through JSON array

I have recently posted another question which straight away users pointed me in the right direction.
$.ajax({
type: 'POST',
url: './',
data: 'token=' + token + '&re=8',
cache: false,
timeout: 5000,
success: function(html) {
auth(html);
var JSON_array = eval(html);
alert(JSON_array[0].username);
}
});
this returns the data correctly but I want to perform a kind of 'foreach'. the array contains data about multiple incoming and outgoing Instant Messages. So if a user is talking to more than one person at a time i need to loop through. the array's structure is as follows.
Array(
[0] => Array
(
[username] => Emmalene
[contents] =>
<ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul>
)
)
Any help very much appreciated.
Well since you are using jQuery already you could use the each function:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000,
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
$('someelement').append(data.contents);
});
}
});
Instead of evaluating the HTML, you can even specify JSON as return type...
Iteration is easy when using $.each:
$.ajax({
type: "POST",
data: ...,
url: url,
dataType: "json",
success: function(data) {
$.each(data, function(i, item){
// do something with every item in data
// you can reference items in data via
// data.fieldName
});
}
});
But a for ... in loop isn't much harder:
$.ajax({
...,
dataType: "json",
success: function(data) {
var fields = data.fieldName;
var value;
for (value in fields) {
// do something with value
}
}
});
Just to clarify, As I've read many helpful hints and answers and only this one worked for me:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, datatype: 'json',
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
var talk_to = JSON_array.username;
var contents_to_update = JSON_array.contents;
});
}
});
this which made work:
1) use of eval.
2) datatype: 'json'
3) use of jquery's $.each function

Categories