3

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.

Codehelp
  • 4,157
  • 9
  • 59
  • 96
  • 1
    Your specifying that the return type is json (`dataType: 'json',`), but your actually returning html. Assuming you do want a view, then you need to return a PartialView and specify `dataType: 'html',` –  May 04 '15 at 09:27
  • @StephenMuecke.. I have a doubt here!! Isn't that `success` necessary in `$.ajax`?? – Guruprasad J Rao May 04 '15 at 09:28
  • 1
    @GuruprasadRao, No, using `.done()` is fine - [this answer](http://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done) explains it –  May 04 '15 at 09:41

1 Answers1

0

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.

Aneesh R S
  • 3,807
  • 4
  • 23
  • 35