Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ajax done function is not working in ASP.NET -MVC5 application

I am using $ajax jquery function on partial razor view to get another partial view along with strongly typed model data from controller to page--> display in specific div. Now if data model data is there it works but in case if there is no model data, I am passing json response so that I can check on razor view in order to avoid null exception. My issue is done method in $ajax is not calling plus json response, I don't know where I am doing wrong

Ajax function

$(document).ready(function () {

    /*Address*/
    $.ajax({
        url: '@Url.Action("DisplayStudentAddress")',
        type: "GET",
        cache: false
    }).done(function (data, textStatus, jqXHR) {

        alert(data.Response);

       $('#studentAddressDisplay').html(data);

    }).fail(function (jqXHR, textStatus, errorThrown) {

        alert(jqXHR +"    "+textStatus+"    "+errorThrown);
    });
});

ActionResult Method

 [HttpGet]
 [Authorize]
 public ActionResult DisplayStudentAddress()
    {
        int _studentEntityID = 0;

        _studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());

        Address _studentAddressModel = new Address();

        _studentAddressModel = _studentProfileServices.GetStudentAddressByStudentID(_studentEntityID);


        if (_studentAddressModel != null)
        {
            return PartialView("DisplayStudentAddress_Partial", _studentAddressModel);
        }
        else
        {
             return Json(new { Response = "Provide Your Address Detail!" });
        }
    }
    #endregion

I have check in debugging, json is called in controller but it alert error in ajax

like image 578
K.Z Avatar asked Oct 20 '22 06:10

K.Z


1 Answers

If your server returns empty string for a json response, jQuery treats it as failed. and empty string is considered invalid json.

As per official document here.

As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error.

try below code instead with using .always:-

$.ajax({
        url: '@Url.Action("DisplayStudentAddress")',
        type: "GET",
        cache: false
    }).always(function (data, textStatus, jqXHR) {

    alert(data.Response);

   $('#studentAddressDisplay').html(data);

}).fail(function (jqXHR, textStatus, errorThrown) {

        alert(jqXHR +"    "+textStatus+"    "+errorThrown);
    });

Because .done is executed only if everything works successfully so if there will be something wrong .done will not be called. But the always method will always get triggered regardless your ajax request works or not.

like image 165
Neel Avatar answered Oct 22 '22 00:10

Neel