0

I'm trying to pass a list object from the server to an Ajax success callback, but I'm not receiving data in the console, and the alert calls in my code don't fire.

I don't have much experience with JS, and I haven't been able to determine why this isn't working. I've already tried changing ActionResult to JsonResult, to no avail.

This is the action method:

public ActionResult jason()
{
    var list = new CardModel().ItemList;
    return Json(list);
}

And this is the Ajax call:

<script>
  $(document).ready(function() {
    $.ajax({
      type: 'GET',
      url: "/Card/jason/",
      dataType: 'json',
      success: function myfunction(data) {
        console.log(data);
        var list = data;
        console.log(list);
        $.each(list, function(index, item) {
          alert(item);
        });
      }

    });
  });
</script>
IronFlare
  • 2,287
  • 2
  • 17
  • 27
Cavid
  • 125
  • 13
  • Do you mean, you get `undefined` in success callback ? or you do not get anything in console? – random Mar 26 '19 at 17:51
  • I get nothing .. not even undefined – Cavid Mar 26 '19 at 17:52
  • Is it a typo? Your URL is `/Card/jason/` - did you mean `/Card/json/`? – freefaller Mar 26 '19 at 17:52
  • no, my bad, it's misspelled here.. my Action name is "jason" actually not index – Cavid Mar 26 '19 at 17:55
  • Try adding `error` callback. – random Mar 26 '19 at 17:58
  • @randomSoul error message is : Internal Server Error – Cavid Mar 26 '19 at 18:44
  • @Cavid - There is something wrong with your `backend` code. It has nothing to do with the `ajax` request. I mean with the `Get` request url route code. – random Mar 26 '19 at 18:46
  • @randomSoul when page loads I'm getting directed to url - CardController/jason. Inside there I retrieve the list and page finishes the load. So I can't see any error regarding server side.. Maybe I should install any Nuget package for Json serialisizing to begin with? – Cavid Mar 26 '19 at 19:47

2 Answers2

2

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet like

return Json(list, JsonRequestBehavior.AllowGet);

see this link Why is JsonRequestBehavior needed? for details

Muhammad Ali
  • 288
  • 3
  • 12
0

This only happens when your dataType is not correct. Are you sure you're receiving JSON from the backend?

According to the docs: enter image description here

You should be able to see an error in error callback function of ajax()

SerShubham
  • 873
  • 4
  • 10
  • This means that the API you called has failed for some reason. You may want to debug your API. Your jQuery seems to be working fine. – SerShubham Mar 26 '19 at 18:38
  • could it return nothing(no console message or alert) if list count is 0? – Cavid Mar 26 '19 at 18:41