mahmod nasser
mahmod nasser

Reputation: 31

JQuery Ajax , why in success i have error why?

Why in success I have error?

$('#ck').click(function() {
  var StudentData = [{
    'Name': 'Ali',
    'Age': 27
  }, {
    'Name': 'Sam',
    'Age': 32
  }];

  $.ajax({
    url: "/Home/StudentInfo",
    data: JSON.stringify(StudentData),
    ...
    success: function(response) {
      alert(response[0].Name);
    },
    error: function() {
      alert("error");
    },
  });
});

Upvotes: -7

Views: 59

Answers (1)

David
David

Reputation: 219047

Based on an excessively lengthy comment thread above, you claim to have this server-side code:

public JsonResult StudentInfo(List<object> StudentData)
{
    return Json(StudentData);
}

So, you're returning a List<object> to your client-side code. Then in your client-side code you try to access a property on an element in that list:

success: function (response) {
    alert(response[0].Name);
}

Well, to put is simply, object doesn't contain a property called Name. It never has, and it probably never will. So you can't access a property that doesn't exist. Hence, it's undefined in JavaScript.

It looks like you meant to define a class for your objects. Something as simple as this:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Then you can use that class in your action method:

public JsonResult StudentInfo(List<Student> StudentData)
{
    return Json(StudentData);
}

Since Student does have a property called Name, you can use that property in your client-side code.

Upvotes: 0

Related Questions