Search code examples
asp.net-mvcasp.net-mvc-ajax

Failed to call action method from AJAX


I have a JavaScript method dotrack(). I am calling an action UpdateJson from the JavaScript through AJAX. I am passing JSON data type and the method will return true/false. After executing system is going to success block but the returned value is not true/false.

My question is, whether the system is calling the action properly or not.

function doTrack() {
    var D = { 'pageUrl': PageURL, 'linkUrl': linkURL, 'linkName': linkText, 'linkType': ControlType, 'leadId': LeadID, 'userType': UserType, 'portalId': PortalID, 'languageId': LanguageID, 'countryId': CountryID };
    D = JSON.stringify(D);

    $.ajax({
        type: "POST",
        url: "portal/UpdateJson",
        data: D,
        contentType: "application/json; charset=utf-8",
       success: function (result) {
        if(result == true)
            alert("Success");
        else
            alert(result);

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError + " :: " + ajaxOptions);
            //alert('unable to complete ajax request.');
        }
    });
}

Controller is Portal & Action is UpdateJson:

[HttpPost]
public ActionResult UpdateJson(string pageUrl, string linkUrl, string linkName, string linkType, string leadId, string userType, string portalId, string languageId, string countryId)
{
    //do stuff
    return Json(true);
}

Please help.


Solution

  • Your ajax code is working fine.

    You just need to use the result variable directly instead of result.val.

    success: function (result) {
        exists = (result);
        alert(exists);
    }
    

    If you want to use val property, you need to return an object that has val property too.

    return Json(new { val = true });
    

    Also you should use Url.Action for preventing incorrect URL.

    url: "@Url.Action("UpdateJson", "portal")"