404 error when making ajax call to asp.net MVC controller - javascript

I'm trying to make an ajax request to an MVC controller but I keep getting a 404 error whenever I try execute my script.
Failed to load resource: the server responded with a status of 404 ()
https://localhost:44301/LocationMapping/Test
My request just returns error get from the code snippet below.
The structure of the relevant files in my project are
View where request is called -> courselister/index.cshtml
View's Controller -> CourseListerController.cs
My Controller for handling Ajax requests from the above view-> LocationMappingController.cs
The reason I am handling the requests from a different controller is because several views will use the same requests and so it seems better to keep these all together in LocationMappingController.
Here is the code for my ajax request
$(document).ready(function () {
$.ajax({
url: "/LocationMapping/Test",
type: "GET",
dataType: "json",
data: {},
error: function (error) {
alert('error get');
},
success: function (data) {
alert('GET success');
alert(data);
}
});
});
Here is the code in the LocationMapping Controller
public JsonResult Test() {
{
return Json("Get Test", JsonRequestBehavior.AllowGet);
}
My current theory is that the server cannot find the route /LocationMapping/Test because it is not it the view's controller (CourseListerController.cs). It has taken a long time for me already to find a solution and so I am turning to the SO community to help.
Any help is appreciated.
Update: I tried creating a new controller and a view associated with it as follows,
TestAjaxController.cs
public ActionResult Index()
{
return View();
}
public JsonResult GetResponse(string str)
{
return Json(str, JsonRequestBehavior.AllowGet);
}
TestAjaxController/Index.cshtml
<div>
<h1>Test Ajax Page: Location Mapping</h1>
<button onclick="callAjax()">Click Me</button>
<script>
//document.ready(function () {
console.log('jquery loaded');
function callAjax() {
$(document).ready(function () {
alert("called");
jQuery.ajax({
url: "/TestAjax/GetResponse",
type: "GET",
dataType: "json",
data: { str: "this is the string I want to get as a response" },
error: function () {
alert("Error occurred calling GetResponse");
},
success: function (data) {
alert(data);
}
});
});
}
</script>
</div>
and this works! I get prompted with the "this is the string I want to get as a response". I don't understand why it works when my other controller will not..

Faced the same issue. Closed the localhost tab in browser and ran start without debugging. I was able to view the JSON data in the route.

Related

MVC 5 generate form data with AJAX

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

Call c# function with javascript code

I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}

How to make AJAX calls

I am aware this question has been answered before but I am somehow unable to hit an action within my controller.
Here is the Action
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
In my script:
$.ajax({
type: 'GET',
url: '#Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
Using fiddler I can hit GetUpdate but from the browser the Ajax call fails. Am I correctly accessing the URL?
Update:
The following is the error message:
"NetworkError: 404 Not Found - protocol://localhost:port/Controller/#Url.Action(%22GetUpdate%22)"
The following works through Fiddle:
protocol://localhost:port/Controller/GetUpdate
Razor code (C# and all other server-side script) is only executed from .cshtml files, therefore C# and Razor can't be used in .js files.
'#Url.Action("GetUpdate")' doesn't generate a URL, it's just a string, therefore you are trying to request protocol://domain:port/Controller#Url.Action("GetUpdate") which doesn't exist.
Here's what you can do:
In the .cshtml file you can store the generated URL in a JavaScript variable and pass it to the external JS file.
You can move your external JavaScript to the .cshtml file so you can use Razor.
use a relative string path like /Controller/GetUpdate
I would recommend the first one.
You can try this out,where _ApplicationPath is protocol://localhost:port/
$.ajax({
type: 'GET',
url: _ApplicationPath + "/ControllerName/GetUpdate",
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});

AJAX routing is not working for my custom function in Laravel

I am using Laravel 4.2.6
This is my function with an ajax call to the controller's method called savesession
function saveActualSession() {
return $.ajax({
url: 'savesession',
data: {
my_username: $('input#username').val()
},
type: 'POST',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
}
In controller I have this:
public function savesession()
{
if(Request::ajax())
{
$my_username = Input::post('my_username');
if ($my_username) { Session::put('my_username', $my_username); }
return $my_username;
}
}
Sessions saving is triggered like this on different places in my javascript code:
saveActualSession()
.done(function(e) {
// Things to be done after saving session
})
.fail(function(e) {
alert('oh no!')
});
The problem is that it's giving me this error in the console:
"NetworkError: 500 Internal Server Error - http://laravelsite.dev/savesession"
It's weird because the url exists 100%, because when I try to do this in the controller:
public function savesession()
{
if(Request::ajax())
{
$my_username = Input::post('my_username');
if ($my_username) { Session::put('my_username', $my_username); }
return $my_username;
}
else
{
print_r("url is working");
die();
}
}
and I access the url directly in my browser like:
http://laravelsite.dev/savesession
It's giving me the print_r message url is not working and it dies.
btw. my routes look like this:
Route::any('savesession', ['as' => 'savesession','uses' => 'RegistrationController#savesession']);
What am I doing wrong?
I have a similar AJAX function for getting sessions and that route works fine and no server errors are shown.
Any idea?
You have a wrong method there. Simply change...
$my_username = Input::post('my_username');
to this...
$my_username = Input::get('my_username');
Get does not refer to the HTTP Method in this context, it refers to what Laravel is doing - get an input value. This value can be GET or POST, it doesn't actually make a difference.

MVC How to pass data from view to model using Ajax

Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!

Categories