I'm working on a web application that is supposed to use ajax to connect to a database and have basic CRUD functionality. Everything works fine except for the Update. On selection on a database entry I want it to prepopulate the input boxes with the existing data using javascript.
$(document).ready(function() {
$.ajax({
url : '/animal',
method : 'GET'
}).then(function(animals) {
for (var i = 0; i < animals.length; i++) {
var animal = animals[i];
var row = '<option value="' + animal.animalId + '">'
+ animal.commonName
+ '</option>';
$("#animals").append(row);
}
});
$.ajax({
url : '/food',
method : 'GET'
}).then(function(foods) {
for (var i = 0; i < foods.length; i++) {
var food = foods[i];
var row = '<option value="' + food.foodId + '">'
+ food.foodName
+ '</option>';
$("#foods").append(row);
}
});
$("#animals").change(function() {
$.ajax({
url : '/animal/' + $("#animals").val(),
method : 'GET'
}).then(function(task) {
console.log($("#animals").val());
$("#cName").val(animals.commonName);
$("#sName").val(animals.sciName);
$("#food").val(animals.foodId);
$("#infoLink").val(animals.infoLink);
});
});
$("#submit").click(function() {
var animal = {};
animals.commonName = $("#cName").val();
animals.sciName = $("#sName").val();
animals.foodId = $("#food").val();
animals.infoLink = $("#infoLink").val();
$.ajax({
url : '/animal/' + animals.animalId,
method : 'PUT',
data : JSON.stringify(animal),
contentType : 'application/JSON'
}).then(function() {
window.location.href = "/animal/index";
});
});
});
that's the javascript I currently have, and I can't figure out what's wrong. any help is appreciated.