LStarky LStarky - 1 month ago 8
Javascript Question

Creating new record in Aurelia -- error with JSON encoding?

I'm creating an Aurelia app and it successfully pulls records from an API, edits and saves changes to individual records, and deletes individual records. However, I cannot seem to fix a problem with creating new records.

In calendar.js, I have the function newCalendar() which is called by a form button.

newCalendar() {
this.selectedId = this.error = null;
this.calendar = [];
this.calendar.cal_name_tran = "New Calendar";
this.calendar.cal_name_orig = "Nuevo Calendario";
console.log(this.calendar);
console.log(JSON.stringify(this.calendar));
$('#edit_calendar').modal('show');
$('#cal_name_orig').focus();
}


When I click the button, I get the following text in the console log:

[cal_name_tran: "New Calendar", cal_name_orig: "Nuevo Calendario"]
[]


The text "New Calendar" and "Nuevo Calendario" are successfully bound to the View in the Modal form.

<form>
<div class="form-group">
<label class="control-label" for="cal_name_orig">Calendar name</label>
<input type="text" class="form-control" id="cal_name_orig" placeholder="${'Calendar_Example_Name'&t}" value.bind="calendar.cal_name_orig & validate">
</div>
<div class="form-group">
<label class="control-label" for="cal_name_tran">Translated name</label>
<input type="text" class="form-control" id="cal_name_tran" value.bind="calendar.cal_name_tran & validate">
</div>
</form>


However, when I try to save the calendar using the following function, it sends an empty string, same as what is showing up in the second line of the console log (above).

saveCalendar() {
console.log(JSON.stringify(this.calendar));
this.httpClient.fetch("/calendar/new", {
method: 'put',
body: json(this.calendar)
});
}


Why does
JSON.stringify(this.calendar)
results in an empty array when
this.calendar
shows the values of the array?

Answer

Since you want the calendar to contain key-value pairs, you can make it an object (instead of array).

this.calendar = {};

JSON.stringify expects a valid JSON (can be an array then as well). In your example, although you are creating the calendar as an array, you are using it as an object.

If you want it to be an array, you will have to use the push method instead:

this.calendar = [];
this.calendar.push("New Calendar", "Nuevo Calendario");