Javascript Ajax Not Working on ASP.NET C# and Returns a 404

Javascript AJAX not working on ASP.NET C# and returns a 404

You can get help from the code below to send data.

You do not have to submit a string item in the form { ids: theIds } You must change the form to JSON.stringify(data) .

var data = "Your Name";
$.ajax({
url: '/home/Complete',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});

And your class should not be simple. You must have a controller class

Backend:

public class HomeController : Controller
{

[HttpPost]
public void Complete(string Name)
{
//Code ...
}
}

AJAX call returns 404 on server, works locally

Problem solved. I needed to convert my drop-down list into an @Html.DropDownListFor object, and wrap it in a form object like so:

<form id="custNameForm" asp-controller="myController" asp-action="GetLocations" method="post">
@Html.AntiForgeryToken()

@Html.DropDownListFor(x => x.Name, new SelectList((List<string>)ViewBag.custList), "Select Customer",
new { @class="form-control text-center" })
</form>

Next, in my javascript file, I add the following "change" listener:

.on('change', '#CustName', function (e) {
e.preventDefault();
GetLocations(e);
})

...which points to this jquery function:

function GetLocations(e) {
var loc = $('#CustName option:selected').val();
var noLoc = loc === '' || loc === 'Select Customer';

if (!noLoc) {
var form = $('#custNameForm');
var url = form.attr('action');
var token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
__RequestVerificationToken: token,
'loc': loc
},
success: function (data, textStatus, jqXHR) {

var listData = data;
resetLocationList();
for (var listSize = 0; listSize < listData.length; listSize++) {
$('#custLocation').append('<option value="' + listData[listSize] + '">' + listData[listSize] + '</option>');
}

},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error caught: ');
console.log(errorThrown);
}
});
}
else {
parseXML('');
}

$('#custLocation').prop('disabled', noLoc);
}

... where "#custLocation is the ID of the dropdown to be populated with the list of customer locations.

404 Error On Ajax Post

You are getting an error 404 which according to HTTP means Not Found. You probably on the wrong route which doesn't map to any resource.

AJAX 404 Error - Call to controller action .Net MVC

Here's a working demo: https://dotnetfiddle.net/kE5Px7

I just made one change, added the HttpPost attribute to the action you're calling.

[HttpPost]
public JsonResult GetAllPeople()

and as suggested in the comments, the action returns this:

return Json(people);

The URL of the AJAX call remains the same: url: '@Url.Action("GetAllPeople")'.

AJAX POST request returns 404 .NET 6

So I found a my solution. In my Startup.cs I have this code:

    services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
});

And the BadRequest from the Controller came because of the AntiForgeryToken validation. In my AJAX call my header for the AF Token was wrong: It was 'RequestVerificationToken', but it should have been 'X-CSRF-TOKEN' or the other way around. But still now I have the proper result and no more BadRequest.

Calling controller method via ajax reach "404 not found"

Use the controller name prefix Products instead of ProductsController

$(document).ready(function () {
$.ajax({
type: 'POST',
url: '@Url.Action("GetProducts", "Products")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf­8',
data: JSON.stringify(""),
});

Asp.Net-MVC uses a naming convention for controllers.



Related Topics



Leave a reply



Submit