CoderMan
CoderMan

Reputation: 57

ASP.NET MVC Ajax call not working on production server

It works like a charm on the localhost, but not working on production server at all.

My controller method is something like this:

[HttpPost]
public JsonResult VisualizaDebitos()
{
    var filtro = Request["filtro"];
    var emissao = DateTime.Parse(Request["emissao"]);
    var vencimento = DateTime.Parse(Request["vencimento"]);
    var mesCompetencia = int.Parse(Request["mesCompetencia"]);
    var anoCompetencia = int.Parse(Request["anoCompetencia"]);

    return Json(new { data = someprocesseddata }, JsonRequestBehavior.AllowGet);
}

And the ajax call:

$.ajax({
    url: "/Mensalidade/VisualizaDebitos",
    datatype: "json",
    type: "POST",
    data: {
        filtro: $("#Participante").val(),
        emissao: $("#Emissao").val(),
        vencimento: $("#Vencimento").val(),
        mesCompetencia: parseInt($("#MesCompetencia").val()),
        anoCompetencia: parseInt($("#AnoCompetencia").val())
    },
    error: function (data) {
        if (data.status == 500) {
            jAlert('Response status: ' + data.status + ' (' + data.statusText + ')' +
                '\n\nVerifique se a url e/ou os parâmetros estão corretos e tente novamente.', 'Error');
        } else {
            jAlert('Error', 'Unknown error');
        }
    },
    success: function (result) {
        console.log(result.someprocesseddata);
        return false;
    }
});

I'm getting an error 500 internal server error

I'm missing anything?

Upvotes: 1

Views: 5106

Answers (7)

Danimal111
Danimal111

Reputation: 2062

The issue might be database access. You likely have all the code correct if it is working in Staging/ the Dev Server... It works in Dev where you have universal power (admin rights), but your are likely using an application pool to access on the production server and this means you need to add the server as a login to SQL Server (or Database of your choosing).

The following applies to SQL Server... your milage may vary:

  1. Create a new SQL Server Login with the name "Domain\Server$" and click OK (do not try to validate this user by using the "Check Names" option.)

  2. Reopen new user and modify properties and grant permissions as needed.

  3. Refresh your site and wait for the magic.

I know this is an old issue, but this is your long awaited solution (or at least it was for me).

;-)

Upvotes: 0

kalai
kalai

Reputation: 186

You can use url:'@Url.Action("VisualizaDebitos","Mensalidade")' instead of url: "/Mensalidade/VisualizaDebitos".

Upvotes: 2

Raj Baral
Raj Baral

Reputation: 671

I had the exact same issue for the app that I host on server IIS. I got same error message when I tried to call ajax post method. Finally I troubleshoot by using internet explorer on hosted server.

I troubleshoot the issue by disabling "Show friendly HTTP error message" on IE. Disable friendly HTTP error messages to see if the raw content can provide a direction to look more. Steps:

  • Go to menu Tools/Internet Options in your IE.
  • Click on the Advanced tab & then uncheck “Show friendly HTTP error messages” option and then click OK.
  • Now, when on accessing the same web page, much more developer meaningful error message will be shown.

If you want to return the actual error details like exception details, stacktrace on some div element,

<div id="dialog" style="display: none"></div>

you can modified your ajax function as

$.ajax({
    url: "/Mensalidade/VisualizaDebitos",
    datatype: "json",
    type: "POST",
    data: {
        filtro: $("#Participante").val(),
        emissao: $("#Emissao").val(),
        vencimento: $("#Vencimento").val(),
        mesCompetencia: parseInt($("#MesCompetencia").val()),
        anoCompetencia: parseInt($("#AnoCompetencia").val())
    },
    error: OnError
});

And Call the onError function as:

function OnError(xhr, errorType, exception) {
                var responseText;
                $("#dialog").html("");
                try {
                    responseText = jQuery.parseJSON(xhr.responseText);
                    $("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
                    $("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
                    $("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
                    $("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
                } catch (e) {
                    responseText = xhr.responseText;
                    $("#dialog").html(responseText);
                }
                $("#dialog").dialog({
                    title: "jQuery Exception Details",
                    width: 700,
                    buttons: {
                        Close: function () {
                            $(this).dialog('close');
                        }
                    }
                });
            }

Reference: This article

Upvotes: 0

Sunil Kumar
Sunil Kumar

Reputation: 3242

Try to replace your data parameters with following data parameters in your ajax code :

 data: {
        'filtro': $("#Participante").val(),
        'emissao': $("#Emissao").val(),
        'vencimento': $("#Vencimento").val(),
        'mesCompetencia': parseInt($("#MesCompetencia").val()),
        'anoCompetencia': parseInt($("#AnoCompetencia").val())
    },

Upvotes: 0

SilentTremor
SilentTremor

Reputation: 4902

var form = new FormData();
form.append("filtro", $("#Participante").val());
form.append("emissao", "$("#Participante").val());
form.append("vencimento",$("#Vencimento").val());
form.append("mesCompetencia", parseInt($("#MesCompetencia").val()));
form.append("anoCompetencia", "parseInt($("#AnoCompetencia").val()));


var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://",
  "method": "POST",
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

What are you doing there is plain stupid, I'm not gonna explain why, but that it's how you learn. I recommend to define a model and expect that model to be posted on your end point as json data, or get your hands dirty lil' bit https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-helpers-forms-and-validation

Upvotes: 0

Vincentw
Vincentw

Reputation: 184

Try the following:

var RootUrl = '@Url.Content("~/")';

And then adjust the url to this:

url: RootUrl + "Mensalidade/VisualizaDebitos",

Edit: I have tried some things to see how or what, but it seems more of an processing error then an error with the posting. Using the following code:

<input type="text" id="Participante" /><br />
<input type="text" id="Emissao" /><br />
<input type="text" id="Vencimento" /><br />
<input type="text" id="MesCompetencia" /><br />
<input type="text" id="AnoCompetencia" /><br />

<button onclick="test()">gotest</button>

<script>
    function test() {
        $.ajax({
            url: "/Home/VisualizaDebitos",
            datatype: "json",
            type: "POST",
            data: {
                filtro: $("#Participante").val(),
                emissao: $("#Emissao").val(),
                vencimento: $("#Vencimento").val(),
                mesCompetencia: parseInt($("#MesCompetencia").val()),
                anoCompetencia: parseInt($("#AnoCompetencia").val())
            },
            error: function (data) {
                if (data.status == 500) {
                    alert('500');
                } else {
                    alert('Unknown error');
                }
            },
            success: function (result) {
                alert('success');
                return false;
            }
        });
    }
</script>

And the code you have in your HTTPPost, it all seems to work with the following values: Test 01-01-2016 01-01-2016 5 6

However, if i input something else then a date or a number in the textboxes, it throws an 500 error. So how is the input from this? is the formatting correct?

Upvotes: 2

Anand Systematix
Anand Systematix

Reputation: 632

Please try 1 thing, replace below url with full path and check if it works.

url: "/Mensalidade/VisualizaDebitos",

If it works then need to use absolute path.

Edited:-

Or please only send string value in post parameter and test. Like you are sending int value, make it string and you can convert it to int in controller method.

Upvotes: 0

Related Questions