JQuery Ajax call gives 404 "Resource not found" error, but regular URL 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 error not found). But when I use a regular GET URL call, I can successfully call the server without any problems. Any idea why this is?

This 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, ViewRecord/GetSoftwareChoice not found on the server, as for the AJAX call.

But if I print this in my web browser:

 http://myapp/ViewRecord/GetSoftwareChoice?username=123 

then no problem.

It is very strange.

Just in case 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 enter my code and find that calling the URL ViewRecord/GetSoftwareChoice?username=123 .

Related question: Select an element inside a form that does not work in jQuery

+7
jquery asp.net-mvc
source share
7 answers

I fix this problem using FireBug to show me the query that was generated by jQuery. To my surprise, the URL created

 http://localhost/ViewRecord/ViewRecord/GetSoftwareChoice?username=123 

to call JSON:

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

So I just need to change the $.getJSON string to

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

Alternatively use a slash:

  $.getJSON("/ViewRecord/GetSoftwareChoice", {username:'123'}, 
+4
source share

Instead of hard-coding the url, you can try UrlHelper:

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

Using Firefox Firebug add and see what the jQuery query does ...

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

In addition, I assume that the code you specified is not really the code you are using (which is quite reasonable, I rairly the postal code as it is). Because the

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

The = sign between the username and '123' is invalid JS as far as I know. Therefore, I bet that there is some kind of stupidity in the real code that causes the problem.

+1
source share

Replace the equal sign with a colon:

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

I also had the same problem. After using Firebug, as Graviton did, I saw that my path was unstable, so I changed it to 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 that returns the JSON result for my jQuery. The jQuery function then processes the 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 initially added a new route to try to handle this, but commented on it to allow default routing.

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

0
source share

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

0
source share

All Articles