Ajax call does not load the page but goes into .fail?

Codehelp

this is an MVC application that I am currently working on. So there is a page in which we display a product details. On this page is a link clicking on which loads another page which shows a set of rules to process this product.

Here's what I have tried now:

The controller, doesn't do much for now:

public class ProductRuleController : Controller
{
    [HttpGet]
    public ActionResult GetAllRulesForProduct(string productId)
    {
        return View("AddEditProductRule");
    }
}

The view:

@{
    ViewBag.Title = "Add / Edit Product Rule";
}
<h2>Add / Edit Rule</h2>

The JS

function ShowProductRules() {
var urlToGetProductRules = "/ProductRule/GetAllRulesForProduct/";
var productId = $('#ProductId').val();

if (productId == null) {
    alert('Please Check the ProductId');
}
else {
    // Make an ajax call passing in the ProductId
    alert('ProductId: ' + productId);
    $.ajax({
        type: "Get",
        url: urlToGetProductRules,
        data: { productId: productId },
        dataType: "json"
    })
        .done(function (data) {

        })
        .fail(function (xhr) {
            alert("Something went wrong!!!")
            console.log(xhr.responseText);
        });
}

The ajax call goes into the .fail part. I inspected the responseText and that has the rquired HTML in it without any errors.

So my question is when the response has the desired HTML in it why is it going to the Fail part? What am I doing wrong?

Thanks in advance.

Aneesh R S

remove the dataType: "json" part from the ajax call

that is

$.ajax({
        type: "Get",
        url: urlToGetProductRules,
        data: { productId: productId },
    })
        .done(function (data) {

        })
        .fail(function (xhr) {
            alert("Something went wrong!!!")
            console.log(xhr.responseText);
        });

When you specifies dataType : "json", the ajax call will expect a json response.If its html, it will count it as an error so the fail part will execute.If you still want to use dataType : "json", then convert the response to json format.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related