Tutorial :JQuery Ajax call gives 404 'Resource Not Found' Error but Normal URL Call is Fine


I have a weird problem when using JQuery call in my ASP.NET MVC project. I found that the Ajax call gives 404 ( resource not found error). But when I use the usual URL GET call, I can successfully call the server without any problem. Any idea why this is so?

This my ASP.NET MVC code

public class ViewRecordController: Controller  {    public JSONResult GetSoftwareChoice(string username)    {       return Json(username);    }  }  

This is my JQuery code:

$(function() {  $("#username").click(function() {          $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},      function(data) {          alert(data);      });      });  });  

The above JQuery gives me a 404 error. Apparently the ViewRecord/GetSoftwareChoice is not found on server, as far as the AJAX call is concerned.

But if I type this in my web browser:


then there is no problem.

This is very weird, indeed.

Just in case if you are interested, this is my route:

public static void RegisterRoutes(RouteCollection routes)  {      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");        routes.MapRoute(          "Default",                                              // Route name          "{controller}/{action}/{id}",                           // URL with parameters          new { controller = "Home", action = "Index", id = "" }  // Parameter defaults      );    }  

Edit: I step into my code, and found that the URL call is ViewRecord/GetSoftwareChoice?username=123.

Related question: Select Element inside Form not working in JQuery


Instead of hard-coding the URL, you might want to try a UrlHelper:

$(function() {      $("#username").click(function() {          var url = '<%= UrlHelper.Action("GetSoftwareChoice", "ViewRecord") %>';          $.getJSON(url, {username: '123'}, function(data) {              alert(data);          });      });  });  


I fix this problem by using FireBug to show me the request that was generated by JQuery. To my amazement, the url generated is


for the JSON call:

$(function() {  $("#username").click(function() {          $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},      function(data) {          alert(data);      });      });  });  

So I just have to change the $.getJSON line to

$.getJSON("GetSoftwareChoice", {username:'123'},  

Alternatively, use the forward slash:

 $.getJSON("/ViewRecord/GetSoftwareChoice", {username:'123'},  


$(function() {      $("#username").click(function() {          $.getJSON('<%= Url.Action("GetSoftwareChoice", "ViewRecord")%>',{username: '123'}, function(data) {              alert(data);          });      });  });  


Use Firefox Firebug add on, and watch what request gets made by Jquery...

Is it possible that the page that this Jquery runs in is in a subdirectory, in which case the request will not be relative root as the http://myapp/ "typed in" url is?

Also, I am guessing the code you specified above is not actually the code you are using (which is completely reasonable, I rairly post code as-is). Because

$.getJSON("ViewRecord/GetSoftwareChoice", {username='123'},  

the = sign between username and '123' is invalid JS as far as I know. So I'm betting there is some goofy detail in the the real code that is causing the problem.


Replace the equal sign with a colon:

$(function() {  $("#username").click(function() {          $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},      function(data) {          alert(data);      });      });  });  


I also had the same problem. After using Firebug as Graviton had done, I saw that my path was wonky so I changed it to just the name of my action. Get_OrderLine is the name of my action in my controller. inv_item_id is the parameter passed to the controller action.

// Update OrderLine data by returning a JSON result  $('#itemsddl').click(function (e) {      var selectedItem = $(this).val();      var actionURL = "Get_OrderLine";      var d = "inv_item_id=" + selectedItem;      var uom = $('#uom');      var size = $('#size');      var unitLbs = $('#unitLbs');      var totalLbs = $('#totalLbs');      var shipName = $('#shipName');      var hazardClass = $('#hazardClass');      var unnaNo = $('#unnaNo');      var packingGroup = $('#packingGroup');      var placard = $('#placard');      var ergNo = $('#ergNo');      $.ajax({          cache: false,          type: 'GET',          url: actionURL,           data: d,          datatype: JSON,          success: function (data) {              uom.val(data.uom);              size.val(data.size);              unitLbs.val(data.unitLbs);              totalLbs.val(data.totalLbs);              shipName.val(data.shipName);              hazardClass.val(data.hazardClass);              unnaNo.val(data.unnaNo);              packingGroup.val(data.packingGroup);              placard.val(data.placard);              ergNo.val(data.ergNo);          },          error: function (xhr, ajaxOptions, thrownError) {              alert('Failed to query item - ' + thrownError + "\n" + "Full details: " + xhr.responseText);          }      });      e.preventDefault();  });  

This is my action which returns a JSON result to my jQuery. The jQuery function then handles mapping from JSON to HTML. Not very pretty, but it works.

public ActionResult Get_OrderLine(int? inv_item_id)  {      HazmatInfoItem item = new HazmatInfoItem();      item.itemId = "0";      item.size = "0";      item.unitLbs = 0;      item.qty = 0;      item.totalLbs = item.qty * item.unitLbs;      item.shipName = "";      item.hazardClass = "";      item.unnaNo = "";      item.packingGroup = "";      item.placard = "";      item.ergNo = "";        var items = from i in hazmatRepository.GetAllItems()                  select i;        // Get item details      items = items.Where(i => i.INV_ITEM_ID.Contains(inv_item_id.ToString()));        foreach (var i in items)      {          item.uom = i.UNIT_MEASURE_STD;          item.size = i.INV_ITEM_SIZE;          item.unitLbs = 1;          item.totalLbs = item.unitLbs * item.qty;          item.shipName = i.PAG_SHIPPING_NAME;          item.hazardClass = i.HAZ_CLASS_CD;          item.unnaNo = i.MSDS_ID;          item.packingGroup = i.PACKING_CD;          item.placard = i.PAG_PLACARD_TYPE;      }        return Json(item, JsonRequestBehavior.AllowGet);  }  

I had originally added a new route to try to handle this, but commented it out to allow the default routing.

Hopefully these solutions can help someone else who has had a similar problem when trying to use .ajax with jQuery and MVC.


Old function :

function Chart() {        var url = "../Home/Pie/";      $.ajax({          url: url,          data: {},          cache: false,          type: "POST",          success: function (data) {              var chartData = data;              createChart(chartData);              $(document).bind("kendo:skinChange", createChart);          },          error: function (xhr, status, error) {              $('#alertdialog').html(status);              $('#alertdialog').dialog('open');              return false;          }      });  }  

Answers : var url = "Home/Pie/"; Removed ../ from url

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »