Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax Post - Action returns Partial View but does not hit success or displays

I am making a call to a controller action as follows:

$j.ajax({
    url: url,
    type: "post",
    data: JSON.stringify(commentParam),
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (data, status, jqxhr) {
        $j('#' + commentsCtrlId + ' ul').prepend(data);
        commentField.val('');
    },
    failure: function () {
        alert("Error adding comment");
    }
});

Where the Action looks like:

    [HttpPost]
    public ActionResult Create(string commentBody, int parentObjectId, string parentObjectType, int actionId = 0)
    {
        try
        {

        // code to check security and pass info to the database. A comment model object is then passed back to the partial view

            return PartialView("_Comment", comment);
        }
        catch (Exception ex)
        {
            Logger.Instance.LogError("Error in CommentController Create", ex);
            return View("Error");
        }
    }

I can break on this method and the data is passed to the database okay.

I can break point on the Partial View so can see the data is being passed there okay, however when I get back to my ajax call, it never gets a response (neither Success or Failure)! I am not getting any errors any where and absolutely nothing to go on. Does anyone have advice on how I can at least try and debug what is going on here please?

like image 681
CJH Avatar asked Dec 09 '25 06:12

CJH


1 Answers

Your method returns a view (html), so you need to change the dataType option to 'html'

$j.ajax({
    url: url,
    type: "post",
    data: JSON.stringify(commentParam),
    dataType: 'html', // modify
    contentType: "application/json; charset=utf-8",
    success: function (data, status, jqxhr) {

Note also your method should return a PartialView in the catch block (as you did for the try block)

catch (Exception ex)
{
    Logger.Instance.LogError("Error in CommentController Create", ex);
    return PartialView("Error"); // modify
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!