How to add items to an empty array in Javascript - javascript

Controller sends a JSON for one Frame. I need to keep incrementing the array where Multiple Frame's score gets added. For example
FrameScore = f1 + f2 +.. lastF
Issue The values do not get added and shows data for each Frame only. Where am I doing it wrong?
var bowlingData = {
"frames": []
};
var frames = [];
$('#submitButton').click(function(e) {
frames.push([$("#FirstRoll").val(), $("#SecondRoll").val()]);
for (var ln = 0; ln < frames.length; ln++) {
var temp = {
"firstroll": $("#FirstRoll").val(),
"secondroll": $("#SecondRoll").val()
};
bowlingData.frames.push(temp);
}
console.log("temp data: " + temp);
bowlingData.frames.push(temp);
var element = this;
$.ajax({
url: "/Home/Submit",
type: "POST",
data: JSON.stringify(bowlingData),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
var parseData = JSON.parse(data);
console.log("MyDate: " + data.score);
console.log("Parse" + parseData);
$("#lblTotalScore").text(parseData.score);
$("#FirstRoll").val("");
$("#SecondRoll").val("");
},
error: function() {
alert("An error has occured!!!");
}
});
});

Apparently the solution is
var frameArray= [];
frameArray.push("#FirstRoll");
frameArray.push("#SecondRoll");
But that is to add single elements to the array. If the input is [[2, 3],[4, 5],...] then the JSON object representation would be
{ "frames": [{"first": 2, "second": 3}, {"first": 4, "second": 5}, ... ] }
However, there was another issue of not getting the correct response from the controller.
The issue here is that an empty array is created (i.e. frames) and on the 3rd line the value was pused to the empty Array. Although the the for loop was adding each element to the Array(i.e. frames) but when the response was created the recent input was replacing the previous input, because the JSON object bowlingData was holding temp data only. So no need to create any Array to increment multiple input result. Initial value would be hold by the browser and second input would be added in next submit.
Was
var frames = [];
$('#submitButton').click(function(e) {
frames.push([$("#FirstRoll").val(), $("#SecondRoll").val()]);
for (var ln = 0; ln < frames.length; ln++) {
var temp = {
"firstroll": $("#FirstRoll").val(),
"secondroll": $("#SecondRoll").val()
};
bowlingData.frames.push(temp);
}
Should be
$('#submitButton').click(function (e) {
bowlingData.frames.push({
"firstroll": $("#FirstRoll").val(),
"secondroll": $("#SecondRoll").val()
});

Related

Get JSON array data by field name

I'm trying to get JSON data by field name like this data.name and it return the desired data, but I have 25 fields in the array and I want to make this dynamically, using data + "." + variable, when I alert it returns [Object object].name, so how I can make it executable?
I tried many ways but all failed, please help me doing this.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: {
'Arrnagement': Arrnagement
},
success: function(data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = data[0].jid;
alert(resulting);
if (result[i].innerHTML = data[0].jid != "undefined") {
result[i].innerHTML = data[0].jid;
} else {
result[i].innerHTML = "";
}
}
//jid = name;
//data[0].name returns "Joun"
//data[0]+"."+jid returns [object object].name but i need it to return "Joun"
This should work. I changed the dot notation while accessing the object property.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: { 'Arrnagement': Arrnagement },
success: function (data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var responseData = data[0];
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = responseData[jid];
alert(resulting);
if (responseData[jid]) {
result[i].innerHTML = responseData[jid];
}
else {
result[i].innerHTML = "";
}
}
Try giving data[0][jid], we can give a variable in brackets also inorder to get the data
Hope it works
If do foo.bar you are getting a property with the name 'bar' on object foo. If you have some variable const bar = "qux" and you want to access property on some object with the same name as bar value /"qux"/ you just need to use square brackets - foo [bar], which will be the same as calling foo.qux; So, in your case you just need to use data[0][jid] instead of data [0].jid, supposing jid contains a string that is also a key in data[0].
You can just do data[0][variableName] and this will return the data you want. for example. If data had a json string [{ "Name" : "Jane Doe"}] You could execute it like this.
var variableName = "Name";
console.log(data[0][variableName])
This would return "Jane Doe".
if you have your field names in an array you can loop through them using $.each or a for loop.
For example say your json string is [{"First_Name" : "Jane", "Last_Name" : "Doe", "Age" : 32}] you could get all the values from the json string doing this.
var FieldNames = ["First_Name" , "Last_Name", "Age"]
$.each(FieldNames, function(i,item) {
console.log(data[0][item])
}
OR
var FieldNames = ["First_Name" , "Last_Name", "Age"]
for(var i = 0; i < FieldNames.length; i++) {
console.log(data[0][FieldNames[i]])
}

Storing ajax response data into array and compare it to the last values

I am stuck with these. I want to create a function to be run every 4secs. Now My function will get all the queue_id from my database and store it in array again and again, after storing it, i will compare it again and again every 4 secs, if there are changes , then i will do something.
Example execution : If my database response with queue_id's: 1,2,3,4,5 then i will store these data from an array. After storing it, i will query again evry 4 seconds if it returns 1,2,4,5 or 1,2,3,5 i will do something, but if it returns thesame like 1,2,3,4,5 then i will not do something.
I have no idea how to store or create array in javascript . Please help me:
function check_getqueue(clinicID, userID) {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
for(var i=0;i<data.length;i++) {
var tmpCountQ = data[i]['queue_id'];
};
if (tmpCountQ < lastcountQueue) {
}
lastcountQueue = tmpCountQ;
}
});
}
You need to keep track of the lastly received set of ids and compare them with the new ones. When a difference found, call your doSomething() and update the record for next run.
To get things faster you can first check the lengths. More info in the comment blocks below.
var previousQueueIDs = [];
function doSomething() {
// do something
// ...
// set timer for the next run
setTimeout(check_getqueue, 4000);
}
function check_getqueue(clinicID, userID) {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
var queueIDs = [];
if(previousQueueIDs.length != data.length) {
previousQueueIDs = queueIDs;
return doSomething();
}
// length didn't change, so check further
// create new array for the current values
for(var i=0;i<data.length;i++) {
queueIDs.push(+data[i]['queue_id']);
};
// sort them for faster comparison
queueIDs.sort( function(a,b) {
return a-b;
});
// check one by one and exit to run doSomething
// as soon as the first difference found
for(var i=0; i<queueIDs.length; i++) {
if(queueIDs[i] != previousQueueIDs[i]) {
previousQueueIDs = queueIDs;
return doSOmething();
}
}
// no difference this time, just set timer for the next run
setTimeout(check_getqueue, 4000);
}
});
}
Use push, and declare the array outside the ajax request. now all working
function check_getqueue(clinicID, userID) {
var tmpCountQ = [];
var lastCon = [];
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
for(var i=0;i<data.length;i++) {
tmpCountQ.push(data[i]['queue_id']);
};
if(typeof lastCon[0] != "undefined")
{
for(j=0;j < tmpCountQ.length;j++)
{
if(tmpCountQ[j] != lastCon[j])
{
lastCon[j] = tmpCountQ[j];
}
}
}
else
{
lastCon = tmpCountQ;
}
console.log(tmpCountQ);
}
});
}

I want to store the data in an array from the web api

I want to use values from the web api , everything is running fine but when I read values from the url in a single variable it comes as large data:
var orguni = "http://hospdev.hispindia.org/haryana_220/api/organisationUnits?fields=name,id,code";
$.ajax({
type: "GET",
url: orguni,
dataType: "xml",
crossDomain: true,
headers: {
},
success: function (xml) {
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
console.log("UID: "+ ou);
});
}
});
Now when I display ou it returns a list of different id's and I want to use all id's as separate value, can anybody tell me how to do that.
Currently it returns:
index.html:26 UID: g8cMOWx5ydN
index.html:26 UID: Q2FEgPgHvMr
index.html:26 UID: XpIf2v7cJRX
index.html:26 UID: uoPA7guOuLa
index.html:26 UID: BLpdsMuZcqD
When I use console.log(ou[0]); it returns 1st char from each like:
g
Q
x
...
var array = [];
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
array.push(ou);
});
array[0] will now be g8cMOWx5ydN.
What ou[0] is doing is turning g8cMOWx5ydN into an array and returning index 0, which is 'g'.
Edit Following Comment
you can either use the Id as you retrieve it, and not use the array.
$(xml).find('organisationUnit ').each(function () {
var id = $(this).attr('id');
// use id ajax call here
});
or you can use the array after the each
var array = [];
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
array.push(ou);
});
//other code
for(var i=0; i<array.length; i++){
var id = array[i];
// use id ajax call here
}

Javascript - json data not being transferred into memory properly

I have a json file that contains 16,490 lines of data. Here's a snippet:
[
...
["alrightty",2 ],
["alrighttyy",1 ],
["alrighty",100 ],
["alrightyy",1 ],
["alrigt",1 ],
...
]
This data will be used for my sentiment analysis thesis project. I used the following code to extract the data from the json file:
var positive_words_list = {}
function readJSONFile(filename,type) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'json',
success: function(data) {
switch (type) {
case "pos" : positive_words = data; break;
case "neg" : negative_words = data; break;
case "afinn" : afinn_words = data; break;
}
},
async: false
});
}
readJSONFile('js/json/positivekeywords.json','pos');
for (var i = 0; i < positive_words.length; i++) {
row = positive_words[i];
positive_words_list[row[0]] = row[1];
};
What this code does is extract the data from the json file and then put it in a 1-dimensional array with each word as an array index and the number as the value.
Now I have this code run when the site loads inside $(function() { ... }); so positive_words_list should contain the data on load time. The thing is after the site loads and I do positive_words_list.length in the console, it outputs 63. As I said, there should be 16,490 entries.
Did I miss something? What am I doing wrong?
Thanks!
John
EDIT: I should add that when I do a positive_words.length in the console, I get the correct number of elements, 164,950
As far as I can see positive_words_list is a JavaScript object that does not have length property out of the box. So the only reason why you get the magic number 63 is because your array of arrays contain entity with word length as a first item; something like:
[
...
['length', 63],
...
]
In order to get number of keys in JavaScript Object you can either do Object.keys(positive_words_list).length or iterate over all properties and increment the counter:
function size(obj) {
var key,
counter = 0;
for(key in obj) {
if(obj.hasOwnProperty(key)) {
counter++;
}
}
return counter;
}
size(positive_words_list); // <- will return number of properties in object
Your snippet may be modified in the following manner:
HTML
<h1 id="data">Number of positive words is ...</h1>
JavaScript
$(function(){
var positive_words,
positive_words_list = {};
function readJSONFile(filename,type) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'json',
success: function(data) {
switch (type) {
case "pos" : positive_words = data; break;
case "neg" : negative_words = data; break;
case "afinn" : afinn_words = data; break;
}
},
async: false
});
}
readJSONFile('data.json','pos');
for (var i = 0; i < positive_words.length; i++) {
row = positive_words[i];
positive_words_list[row[0]] = row[1];
};
$('#data').html('Number of positive words is ' + Object.keys(positive_words_list).length);
});
Plunker: http://plnkr.co/edit/uhHZ1zEuUHXHIQrd1BVa?p=preview
positive_words_list is an object, not an array, so you should result in:
positive_words_list["alrightty"] === 2
positive_words_list["alrighttyy"] === 1
and so forth. You can get an array of the keys of the object using:
Object.keys(positive_words_list)
Object.keys(positive_words_list).length
Which will return an array of the keys of your object. Note that Object.keys is an ES5 feature available in most current browsers.

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

Categories

Resources