I'm trying to send a JSON Object to my back-end. Basically what I'm trying to do is get the input of 2 textfields and then a list of all selected text boxes. My javascript code so goes like this:
function insertNewHero() {
var selectedAbilities = [];
$('#newhero input:checked').each(function() {
selectedAbilities.push({
"id": $(this).value,
"ability": $(this).textContent
});
});
var superhero = {
"name": document.getElementById("name").value,
"surname": document.getElementById("lastName").value,
"abilities": selectedAbilities
}
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/insertNewHero",
data: JSON.stringify(superhero),
success: function (result) {
// other stuff
}
});
I'm really not an expert yet with javascript, but from what I've found from other anwers and posts this is what I could put together and thought it could actually work. The back-end part is working fine, as I tested it with PostMan and perfectly works fine. This is what the JSON, I;m sending from PostMan, looks like:
{
"name": "Wanda",
"surname": "Maximoff",
"abilities": [
{
"id": 4,
"ability": "Telechinesis"
},
{
"id": 3,
"ability": "Flight"
}
]
}
What could be wrong in the JavaScript code?
Here is a sample of one of the textfields and one of the checkboxes:
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="textfield" class="form-control" id="lastName" placeholder="Last Name" required>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" style="background: #bf0000; color: #bf0000; border: solid #bf0000" id="InsertFlight">
<label class="custom-control-label" for="InsertFlight" value="3">Flight</label>
</div>
Apparently the javascript code is not parsing correctly the value and ids of the checkboxes. How can I make of the checkboxes HTML content, a JSON array correctly formatted