Aaron
Aaron

Reputation: 4480

Getting a 500 error when using an ajax get call

I am getting a 500 Internal Server Error when trying to use an Ajax .get call. I double checked that the method name is the same in the get call as it is in the Route above the method. Not sure why I am getting the 500 error and how to fix it.

Here is my jQuery:

$('button').click(function() {
    $('#New_Note').submit(function(event) {
        event.preventDefault();
        var $form = $(this);
        url = $form.attr("action");

        term = $form.find("input[name='Note']").val();
        console.log(url);

        var posting = $.post( url, { Note: term } );

        var get = $.get("getLastEntry");//This line causes the 500 error                 
    });

Here is my method in my .cs file

[HttpGet]
[Route("getLastEntry")]
public IActionResult GetLastEntry()
{
        ViewBag.Notes = userFactory.GetLast();
        return View();
}

Here is the GetLast method

public IEnumerable<Home> GetLast()
{
            using (IDbConnection dbConnection = Connection)
            {
                dbConnection.Open();
                return dbConnection.Query<Home>("SELECT * FROM notes ORDER BY Id LIMIT 1");
            }
}

Upvotes: 0

Views: 116

Answers (3)

pim
pim

Reputation: 12587

You shouldn't be using GET to make ajax calls. I've seen situations where a bad requests gets cached, and continues to be served despite the code being fine. Switching the protocol to POST will either validate or invalidate my answer for you.

Upvotes: 0

Anton Pavelyev
Anton Pavelyev

Reputation: 489

500 error says that you routing is OK. You have to read error message which the server responds. You can find it in browser (developer tools usually called by F12 hotkey). Also you must have such item <customErrors mode="Off" /> in Web.config.

Error may be in anything: connection string, strange syntax using (IDbConnection dbConnection = Connection) or in .cshtml file.

Upvotes: 1

K D
K D

Reputation: 5989

Can you try following?

  $('button').click(function(){
                   $('#New_Note').submit(function(event){
                       event.preventDefault();
                      var $form = $( this );
                      url = $form.attr( "action" );

                      term = $form.find( "input[name='Note']" ).val();
                      console.log(url);
                      var posting = $.post( url, { Note: term } );

                      var get = $.get("@Url.RouteUrl("getLastEntry")");//Change here                 
                    });

});

Upvotes: 1

Related Questions