Lex Eichner
Lex Eichner

Reputation: 1066

MVC Ajax call not working

I am just learning AJAX and have made a call to my controller but it isn't working.

The problem I am having is that it errors but the alert disappears after a half second and the console error is pretty nonsensical.

Any help would be greatly appreciated.

My jQuery looks like this:

function AjaxVoteClick(itemId) {
    var Url = '@Url.Action("UpVote", "AJAX")' + '?ideaId=' + itemId;

    $.ajax({
        url: Url,
        type: 'POST',
        timeout: 60000,
        dataType: 'json',
        tryCount: 0,
        retryLimit: 3,
        success: function(data) {
            alert("Success");
        },
        error: function (httpRequest, textStatus, errorThrown) {
            alert(httpRequest + "Status = " + textStatus + ", error = " + errorThrown);
        }
    });
}

When I debug it makes the request ok, and with the correct id but then comes back on error.

The controller is doing what it is supposed to do but I will show it anyway:

    [HttpPost]
    public virtual JsonResult UpVote(int ideaId)
    {
        IdeaGenEntities ctx = new IdeaGenEntities();

        var currentIdea = (from m in ctx.Ideas
                          where m.ID == ideaId
                          select m).Single();

        var model = new VoteModel();
        model.Initialize(currentIdea);

        int currentVotes = model.Votes;
        currentVotes += 1;

        currentIdea.Votes = currentVotes;
        ctx.SaveChanges();

        return Json(model);

    }

Looking at the Firebug console gives very little. The error goes after half a second unless I have persist on. Then in the header you have this:

Accept application/json, text/javascript, /; q=0.01 Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Content-Type application/json Cookie __utma=111872281.1986143499.1358265304.1358511066.1358786646.8; __utmz=111872281.1358265304.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ASP.NET_SessionId=natvmbqvjfnm11deiek1hngi; .ASPXAUTH=4C0D282B36C410B3FA8271342C22B0A4435D35CD8F2BFE5B58E3F2A643993963F56D3F410A4E586FC44DC68B5737F9E7EEC18FB32E629014DECAA43B818DC49358E618CA73815EB1BBF977CE04342146B7F5EA30BB7D0D2328FC3B75F1C4CA65 Host localhos Referer localhost User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 X-Requested-With XMLHttpRequest

EDIT: Adding in the Http Fox error.

It says NS_BINDING_ABORTED

and shows this:

(Request-Line) POST /AJAX/UpVote?ideaId=1 HTTP/1.1 Host localhost User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 Accept application/json, text/javascript, /; q=0.01 Accept-Language en-US,en;q=0.5 Accept-Encoding gzip, deflate X-Requested-With XMLHttpRequest Referer localhost Cookie __utma=111872281.1986143499.1358265304.1358511066.1358786646.8; __utmz=111872281.1358265304.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ASP.NET_SessionId=natvmbqvjfnm11deiek1hngi; .ASPXAUTH=4C0D282B36C410B3FA8271342C22B0A4435D35CD8F2BFE5B58E3F2A643993963F56D3F410A4E586FC44DC68B5737F9E7EEC18FB32E629014DECAA43B818DC49358E618CA73815EB1BBF977CE04342146B7F5EA30BB7D0D2328FC3B75F1C4CA65

And in the Content it says: Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)

Upvotes: 0

Views: 1494

Answers (2)

Ramesh
Ramesh

Reputation: 163

$.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         async: false,
         timeout: 60000,
         tryCount: 0,
         retryLimit: 3,
         success: function(data) {
            alert("Success");
         },
         error: function (httpRequest, textStatus, errorThrown) {
            alert(httpRequest + "Status = " + textStatus + ", error = " + errorThrown);
         }
     });

You must specify the content type and if you are working with wcf service your service must be like this

[OperationContract]
    [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]

public virtual JsonResult UpVote(int ideaId)
{
    IdeaGenEntities ctx = new IdeaGenEntities();

    var currentIdea = (from m in ctx.Ideas
                      where m.ID == ideaId
                      select m).Single();

    var model = new VoteModel();
    model.Initialize(currentIdea);

    int currentVotes = model.Votes;
    currentVotes += 1;

    currentIdea.Votes = currentVotes;
    ctx.SaveChanges();

    return Json(model);

}

And if you are using web service your code must contain the following prefix

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public virtual JsonResult UpVote(int ideaId)
    {
        IdeaGenEntities ctx = new IdeaGenEntities();

        var currentIdea = (from m in ctx.Ideas
                          where m.ID == ideaId
                          select m).Single();

        var model = new VoteModel();
        model.Initialize(currentIdea);

        int currentVotes = model.Votes;
        currentVotes += 1;

        currentIdea.Votes = currentVotes;
        ctx.SaveChanges();

        return Json(model);

    }

Upvotes: 1

paul
paul

Reputation: 22001

First thing I'd try is changing you request from POST to GET and:

return Json(model);

to

return Json(model, JsonRequestBehavior.AllowGet);

Upvotes: 0

Related Questions