Javascript scope issue with jquery post and promise - javascript

I am trying to build an array from the responses of a jquery post. I have the following code:
categories_names = [];
$(categories).each(function(index, category_id) {
$.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()},
function(result)
{
categories_names.push = result;
});
}).promise().done(function() {
var final_cats = categories_names.join("");
console.info(final_cats);
});
The post request inserts the category id into a table and returns the name of that category formatted like <li>Category Name here</li> so that once the array is built and all categories selected (by checkbox in the form previous to this) are entered into the database, the array can be joined and inserted as html to the final view. At the moment the code is just printing it out in the console as you can see but as you've probably guessed, it returns (an empty string)
I know this is most likely a scope issue since that's the area of javascript that still totally baffles me, so I'm hoping someone can shed some light on it.

Your .promise().done(...) isn't doing what you think it is. It's simply resolving instantly because there are no animations on the elements you are iterating over. Also, your syntax for [].push is wrong.
var defArr = $(categories).map(function(index, category_id) {
return $.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()});
}).get();
$.when.apply(null,defArr).done(function() {
//var categories_names = [];
//for (var i = 0; i < arguments.length; i++) {
// categories_names.push(arguments[i][0]);
//}
var categories_names = $.map(arguments,function(i,arr) {
return arr[0];
});
var final_cats = categories_names.join("");
console.info(final_cats);
});

categories_names.push = result;
can you try changing this to
categories_names.push(result);
because push is a method, not a variable.

Related

Updating the value of an object inside a loop using javascript

I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.

TypeError: 'undefined' is not an object in Javascript

I have a piece of Javascript code that assigns string of values to a string array.
Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.
_popupButtonClick: function (button) {
var solutions = this._stateModel.get('solutionName');
var i;
var solutionsLength = solutions.length;
var selectedSolution = [solutionsLength];
this.clearPopupTimer();
if (button.position === StatusViewModel.ResponseType.Ok) {
for(i=0;i<solutionsLength;i++)
{
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
this._stateModel.save({
selectedsolutions: selectedSolution,
viewResponse: StatusViewModel.ResponseType.Ok
});
} else {
this._stateModel.save({
viewResponse: StatusViewModel.ResponseType.Cancel
});
}
}
Change
var selectedSolution = [solutionsLength];
to
var selectedSolution = [];
This makes your array have an extra item that might be causing a crash.
Also,
you have an
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
But no corresponding else, so your array has undefined values for i which are not entering the if.
Maybe adding an empty string might solve it:
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
else
{
selectedSolution[i] = "";
}
The code is looking fine but there seems to be a piece of code which can cause error. For example, you are assigning var selectedSolution = [solutionsLength]; and for example solutionsLength is 5 then your loop runs for 5 times
for(i=0;i<solutionsLength;i++) // runs for 5 times
{
if(this._list.listItems[i].selected)
{
// but selectedSolution = [5]; which is on 0th index and from 1st to 4th index it is undefined
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
So you can try to use push() like
selectedSolution.push(this._list.listItems[i].options.value);
and on initialization change it like,
var selectedSolution = [];
Hopefully this will solve your problem.
var selectedSolution = [solutionsLength];
keeps the value in the selectedSolution variable.
var selectedSolution = [3];
selectedSolution[0] gives the values as 3
So make it simple
var selectedSolution = [];

Underscore.js `filter` not working

I have the following code snippet I use to choose which suburbs from a list the user has selected (with irrelevant code omitted):
var allSuburbsList = new Array([{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}]);
var a3burbs = _.filter(allSuburbsList, function(s) { return s.SuburbAreaID === 3; });
// 3 is a test value. All the test suburbs so far fall under area no. 3.
With this filter, a3burbs comes out as an empty array, []. If I cheat and make the filter:
var a3burbs = _.filter(allSuburbsList, function(s) { return true; });
then a3bubrs comes out an exact copy of allSuburbsList, with all suburbs included. What could I be doing wrong? I'm using the same syntax as indicated on the Underscore.js home page.
Btw, would the way I populate allSuburbsList from a viewmodel array property have anything to do with this:
var allSuburbsList = new Array(#Html.Raw(JsonConvert.SerializeObject(Model.AllSuburbs)));
Just for interest, my first attempt was the hideous code below, but it worked:
var a3burbs = [];
#{for (var i = 0; i < Model.AllSuburbs.Length; i++) {
#:if (allSuburbsList[#i].SuburbAreaID === 3) {
#:a3burbs.push(allSuburbsList[#i]);
};
};
You're creating a new array and passing in an array.
Change it to
var allSuburbsList = [{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}];
Using new Array([{}]), you are creating an array inside another array. Just instantiate that without new Array()

JavaScript stop referencing object after pass it to a function

I know JavaScript passes Objects by reference and thus I'm having a lot of trouble with the following code:
function doGradeAssignmentContent(dtos) {
var x = 5;
var allPages = [];
var stage = new App.UI.PopUpDisplay.PopUpStageAssignmentGrader(null, that);// pass launch element
for(var i = 0; i < dtos[0].result.students.length; ++i) {
var pagesSet = [];
for(var j = 0; j < dtos[0].result.questions.length; ++j) {
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
if(dtos[0].result.students[i].answers[j].assignmentQuestionId === questionObject.questionId) {// expected, if not here something is wrong
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
questionObject.pointsReceived = dtos[0].result.students[i].answers[j].pointsReceived;
} else {
var theAnswer = findAssociatedStudentAnswer(questionObject.questionId, dtos[0].result.students[i].answers[j]);
if(theAnswer !== null) {
questionObject.answer = theAnswer.studentAnswer;
questionObject.pointsReceived = theAnswer.pointsReceived;
} else {
alert("Unexpected error. Please refresh and try again.");
}
}
pagesSet[pagesSet.length] = new App.UI.PopUpDisplay.StageAssignmentGradingPages[dtos[0].result.questions[j].questionType.charAt(0).toUpperCase() + dtos[0].result.questions[j].questionType.slice(1) + "QuestionAssignmentGradingPage"](j + 1, questionObject);
}
var studentInfo = {};
studentInfo.avatar = dtos[0].result.students[i].avatar;
studentInfo.displayName = dtos[0].result.students[i].displayName;
stage.addPageSet(pagesSet, studentInfo);
}
stage.launch();
}
First let me show you what the result (dtos) looks like so you can better understand how this function is parsing it:
The result (dtos) is an Object and looks something like:
dtos Array
dtos[0], static always here
dtos[0].result, static always here
dtos[0].questions Array
dtos[0].questions.index0 - indexN. This describes our Questions, each one is an Object
dtos[0].students Array
dtos[0].students[0]-[n].answers Array. Each student array/Object has an Answers array. Each student will have as many elements in this answers Array that there were questions in dtos[0].questions. Each element is an Object
Now what we do in this here is create this Object stage. Important things here are it has an array called "this.studentsPages". This array will ultimately have as many entries as there were students in dtos[0].students.
So we loop through this for loop disecting the dtos array and creating a pagesSet array. Here comes my problem. On the first iteration through the for loop I create this questionObject element. I also have tried just doing var questionObject = {}, but what you see now was just an attempt to fix the problem I was seeing, but it didn't work either.
So at the end of the first iteration of the outer for loop I call stage.addPageSet, this is what happens here:
var pageObject = [];
pageObject["questions"] = pageSet;
pageObject["displayName"] = studentInfo.displayName;
this.studentsPages[this.studentsPages.length] = pageObject;
if(this.studentsPages.length === 1) {// first time only
for(var i = 0; i < pageSet.length; ++i) {
this.addPage(pageSet[i]);
}
}
The important thing to take notice of here is where I add pageObject on to this.studentsPages which was an empty array before the first call. pageObject now has pageSet plus a little bit more information. Remember, pageSet was an Object and thus passed by reference.
On the next iteration of the for loop, when I hit this line:
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
It goes wrong. This changes the local copy of questionObject, BUT it also changes the copy of questionObjec that was passed to addPageSet and added to the studentsPages array in the first iteration. So, if I only had 2 students coming in, then when all is said and done, studentsPages hold 2 identical Objects. This should not be true.
The problem is questionObject in the doGradeAssignmentContent function is keeping a reference to the Object created on the previous iteration and then overrides it on all subsequent iterations.
What can I do to fix this?
Thanks for the help!
With out having looked at it too closely I believe you need to change the following:
// Before:
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
// After:
var questionObject = jQuery.extend(true, {}, dtos[0].result.questions[j]);
I didn't look too closely if there are other instances in the code where this needs to be applied, but the core concept is to utilize jQuery's deep copy to generate a duplicate of the object you do not wish to retain a reference to.

Can anyone help with this (Javascript arrays)?

Hi I am new to Netui and Javascript so go easy on me please. I have a form that is populated with container.item data retuned from a database. I am adding a checkbox beside each repeater item returned and I want to add the container item data to an array when one of the checkboxes is checked for future processing.
The old code used Anchor tag to capture the data but that does not work for me.
<!--netui:parameter name="lineupNo" value="{container.item.lineupIdent.lineupNo}" />
here is my checkbox that is a repeater.
<netui:checkBox dataSource="{pageFlow.checkIsSelected}" onClick="checkBoxClicked()" tagId="pceChecked"/>
this is my Javascript function so far but I want to a way to store the container.item.lineupIdent.lineupNo in the array.
function checkBoxClicked()
{
var checkedPce = [];
var elem = document.getElementById("PceList").elements;
for (var i = 0; i < elem.length; i ++)
{
if (elem[i].name == netui_names.pceChecked)
{
if (elem[i].checked == true)
{
//do some code. }
}
}
}
I hope this is enough info for someone to help me. I have searched the web but could not find any examples.
Thanks.
var checkedPce = new Array();
//some other code
checkedPce[0] = stuff_you_want_to_add
If you merely want to add a value to an array, you can use this code:
var array = [];
array[array.length] = /* your value */;
You may need to use a dictionary approach instead:
var dictionary = {};
function yourCode(element) {
var item = dictionary[element.id];
if (item == null) {
item = /* create the object */;
dictionary[element.id] = item;
}
// Use the item.
}

Categories

Resources