0

I have error although console dispays value of $("#surname").val(). May be script works before form is dynamic building?

  $(function () {
    $("#addEmployeForm").submit(function (event) {
        event.preventDefault();
        $.ajax({
            url: "/api/values/",
            type: "POST",
            data: {
                Name: $("#name").val(),
                Surname: $("#surname").val(),
                Age: $("#age").val(),
                Salary: $("#salary").val(),
                PhoneNumber: $("#phoneNumber").val(),
                Department: $("#department:selected").val()
            },
            success: function (data) {
                $("#resultSpan").html(data[1].Surname)                
            },
            error: function () {
                console.log($("#surname").val());
            }
        });
        console.log("after ajax: " + $("#surname").val());

    });
});
  • Which line ? You have multiple usage of $("#surname").val(). – Dessauges Antoine Oct 13 '17 at 13:16
  • Can you be any more specific about the error? – Drummad Oct 13 '17 at 13:17
  • The only place you're trying to access a `Surname` property is here: `data[1].Surname`, so that's where your issue is. can you `console.log(data)` in your success function to see what's being returned? – Nick Oct 13 '17 at 13:17
  • Unless the returning object from the success call back has the same structure and content as your sending object, your success call back won't work because data[1] is referencing the returning object, not the sending object. – Eliellel Oct 13 '17 at 13:23

1 Answers1

0

The error you're getting suggests the AJAX call was successful, but there is no such object as data[1] being referenced in the following code: $("#resultSpan").html(data[1].Surname). I recommend console.log(data) where you're trying to access data[1] to see what data is actually being returned from your AJAX call.

Nick
  • 16,066
  • 3
  • 16
  • 32