1

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?

CoderMan
  • 59
  • 1
  • 6
  • 2
    Use URL in this way :`@Url.Action("VisualizaDebitos", "Mensalidade")` – Divyang Desai Oct 10 '16 at 12:56
  • 2
    You said 500 error... what are the details of the exception? – Jason P Oct 10 '16 at 12:57
  • When you put a breakpoint on the controller, does it hit the breakpoint? If yes, do you get all the values? – Jordec Oct 10 '16 at 12:57
  • @mybirthname Nothing more than that: error 500 internal server error :( – CoderMan Oct 10 '16 at 13:00
  • Change all your parsing to TryParse, probably some of Request[X] is not valid datetime or int – mybirthname Oct 10 '16 at 13:00
  • @JorisDecraecker Yes it hit when I pass up to two parameters. But when a try to pass the date parameter it rases the error again :'(.... – CoderMan Oct 10 '16 at 13:03
  • How you debug production code??? – Divyang Desai Oct 10 '16 at 13:04
  • @Div It's possible with Azure. But our application isn't on Azure yet. I'm publishing the entire application every time while trying to fix this problem. I'll try to implement the ideas here and come back with the result soon... Thanks. – CoderMan Oct 10 '16 at 13:20
  • @CoderMan What you should really implement is proper error logging. That way, when an exception occurs, you can look at your logs and track down the problem. – Jason P Oct 10 '16 at 14:25
  • @CoderMan, Really it's working on local, because here you are passing data trough ajax but i cannot see that on method.. – Divyang Desai Oct 10 '16 at 16:45
  • @Div I think you're expecting this: public JsonResult VisualizaDebitos(DateTime emissao, [...]) But this way works properly too: var emissao = DateTime.Parse(Request["emissao"]); – CoderMan Oct 10 '16 at 16:59
  • @CoderMan, yeah, this is just get the data from request, like take it from fromcollection – Divyang Desai Oct 10 '16 at 17:01
  • @CoderMan, *I'm publishing the entire application every time while trying to fix this problem*. No need to publish every time. See here all answer indicates to change it in js file or view file were this code located, so need to just modify that file only! – Divyang Desai Oct 10 '16 at 17:02
  • @CoderMan No one can get actually root cause of your issue, you can able to see the actual error in chrome console by clicking on the POST request under Network tab, then viewing the preview tab. This displayed the actual error message. – Divyang Desai Oct 10 '16 at 17:06
  • @Div Yep, you're right. All the changes needed on the js file I can save and refresh the browser. But I will need publish the changes on my controller. Unfortunately it ins't an ASP.NET core self hosted app where I can make changes on the controller in real time. And in the network tab like you said I can't see more than that old error 500 Internal Server Error... – CoderMan Oct 10 '16 at 17:21
  • @CoderMan, Could you add that console screen in the question. And one more thing here you have written *It works like a charm on the localhost, but not working on production server at all.* Did you tested on IIS ? – Divyang Desai Oct 10 '16 at 17:25
  • @CoderMan here no need of `JsonRequestBehavior.AllowGet` because it's use only for `GET` method. – Divyang Desai Oct 10 '16 at 17:29
  • This is pure database access as far as I can see... Add the server as a login and grant access to DB to your SQL Server (or DB of choice)... Use "Domain\Server$" as Login Name - the $ is important... add it to your server name when creating and do not use the "Check Names" option... Simple Access Issue. See my answer below for more details. – Danimal111 Nov 16 '21 at 18:47

8 Answers8

2

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?

Vincentw
  • 164
  • 3
  • 17
  • It worked with just a String parameter like I said, so I think it not a url problem. – CoderMan Oct 10 '16 at 13:23
  • I noticed that the date parameters is passed in with its url encoding equivalent: filtro=2030%2C1078&emissao=10%2F10%2F2016&vencimento=05%2F11%2F2016&mesCompetencia=10&anoCompetencia=2016 don't see nothing wrong with that. – CoderMan Oct 10 '16 at 13:41
  • After testing with your data, the problem is with the second datetime. When i run the test with the date 05/11‌​/2016 i get a 500 error. when i test with 11/05/2016 it works. – Vincentw Oct 10 '16 at 13:44
2

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

YakovL
  • 7,557
  • 12
  • 62
  • 102
kalai
  • 187
  • 11
0

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.

Anand Systematix
  • 632
  • 5
  • 15
  • I also tried stringify everything with "JSON.stringify()" method when the String parameter woked. But not worked too... Its driving me crazy! – CoderMan Oct 10 '16 at 13:44
  • please have a look on :- http://stackoverflow.com/questions/4789613/ajax-500-internal-server-error – Anand Systematix Oct 10 '16 at 13:47
  • Unfortunately none of these response worked. But I think it's not a Ajax call issue. It seems like the problem is with the server or with the IIS to be more specific. After some change (all tips here included) I'm getting some different error on the network tab like @Div said. See the following images: [img-1](https://s21.postimg.org/fz6r1ww4n/image.png) [img-2](https://s21.postimg.org/s2c2ph76v/image.png) [img-3](https://s14.postimg.org/78vu85srl/image.png) More ideas? – CoderMan Oct 13 '16 at 17:35
  • Are you using "Process()" in your code? Have you specified hardcoded path in code? – Anand Systematix Oct 14 '16 at 07:25
  • Yes!! Bingo!! Was missing an exe file along with the last deploy. Thank you everyone! And sorry for the late reply ;) – CoderMan Oct 17 '16 at 12:16
0
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

SilentTremor
  • 4,747
  • 2
  • 21
  • 34
0

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())
    },
Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
0

Unfortunately none of these responses helped me. But I think it's not a Ajax call issue. It seems like the problem is with the server or with the IIS to be more specific. After some changes (all tips here included) I'm getting some different error on the network tab like @Div said.

See the images:

  • https:// s21.postimg.org/fz6r1ww4n/image.png
  • https:// s21.postimg.org/s2c2ph76v/image.png
  • https:// s14.postimg.org/78vu85srl/image.png

More ideas?

CoderMan
  • 59
  • 1
  • 6
0

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

Raj Baral
  • 661
  • 6
  • 19
0

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).

;-)

Danimal111
  • 1,976
  • 25
  • 31