Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server responded with a status of 500 (Internal Server Error) when using Ajax

Hello I have a ajax call:

 $.ajax({
        url: "/Orders/CheckIfExists",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data: {
            catalogNumber: viewModel.catalogNumber,
            quantity: viewModel.quantity
        },
        error: function (data) {
            alert("wystąpił nieokreślony błąd " + data);
        },
        success: function (data) {
            if(data.ok)
            {
                alert(data.quantity)
            }
        }
    })
});

and here's controller method:

public JsonResult CheckIfExists(string catalogNumber, int quantity)
    {
        List<Expression<Func<DeviceInstance, bool>>> where = new List<Expression<Func<DeviceInstance, bool>>>();
        where.Add(w=>w.DeviceUsage.UserId==1);
        where.Add(w => w.Project == null);
        where.Add(w => w.Device.CatalogNo == catalogNumber);
        var result = unitOfWork.deviceInstanceRepository.Get(where)
          .GroupBy(w => new
          {
              DeviceId = w.DeviceId,
              CatalogName = w.Device.CatalogNo,
          })
          .Select(s => new
          {
              Quantity = s.Sum(x => x.Quantity),
          }).First();
        if (result.Quantity >= quantity)
        {
            return Json(new { ok = true, quantity = result.Quantity});

        }
        return Json(new { ok = false });
    }

But I'm always getting Internal 500 error. Data is received by method and all calculations are ok. I compose return JSON as in example. Where I made a mistake?

like image 494
szpic Avatar asked May 23 '14 10:05

szpic


People also ask

How do you resolve the Failed to load resource the server responded with a status 500 internal server error?

Solution 1 A 500 internal server error just means something went wrong with your code. You'll need to examine your server logs to find out what the problem is and fix it.

What is status 500 internal server error?

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. This error response is a generic "catch-all" response.


1 Answers

By default ASP.NET MVC rejects ajax GET requests, you have to allow it by explicitly setting JsonRequestBehavior to AllowGet:

return Json(new { ok = true, quantity = result.Quantity},
    JsonRequestBehavior.AllowGet);
like image 182
Zabavsky Avatar answered Oct 01 '22 21:10

Zabavsky