Ajax call to method on controller is not working - javascript

I'm quite new to MVC and I'm trying to call a method int one of my controllers.
<script>
function checkCardNumber() {
var content = $('#card-number').val();
var url = "AccountController/CheckRegisteredCard";
alert("content and URL are set");
$.post(url, { cardNumber: content }, function (data) {
alert(data);
});
alert("called outside of Post");
}
</script>
and here's the C# controller side:
[HttpPost]
public string CheckRegisteredCard(string cardNumber)
{
if (/*some condition*/)
{
return "";
}
else
{
return "some string";
}
}
both alerts("content and URL are set", "called outside of post") are being triggered, but the ajax part is not working at all. What am I doing wrong here?

If your controller class is called AccountController, the url should be /Account/CheckRegisteredCard.
Have you checked the network tab of your browser? I bet there's a 404 error.
If this snippet of javascript is in a .cshtml file, I would recommend using #Url.Action() to get the url string.

I would recommend using Fiddler and having that open when the ajax call is being made. This will tell you (1) if the call is being made at all or failing immediately, and (2) what kind of response you are receiving from the controller. Also agree with Jason P about how the url should be calling the controller.

Related

AJAX POST request in Spring-MVC does not works

I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser

calling action method from Jquery and redirecting the user to an external site

I would like to call the mvc controller action method from jQuery, and when the action method gets invoked, the user should be transferred to another site. I have tried using jquery ajax to do this but after response.redirect, my page still stays on the same URL with out any change.
$.ajax({
url: '/Controller/Action',
success: function (Data) {
//don't want to use this callback as I require only calling the
action method
}
});
and in the controller
public void Action(){
// process the request and redirect
Response.Redirect("url", false);
}
Can anyone help me in understanding where the issue is in the above code.
Thanks in advance.
You can try something like this
return Redirect("http://www.google.com");
or try using javascript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';
</script>");
}
You can check this link to know about Redirect vs RedirectResult
return new RedirectResult() vs return Redirect()
I tried it and it is working. I hope this helps :-)
HTML
<button class="btn btn-primary" onclick="RedirectTosite()">Redirect To Google</button>
Jquery Call
function RedirectTosite() {
$.ajax({
url: '/Employee/RedirectTosite',
success: function (Data)
{
window.location = Data;
}
});
}
Controller
public JsonResult RedirectTosite()
{
return Json("http://www.google.com", JsonRequestBehavior.AllowGet);
}
I don't get a clue why are you calling server using ajax if you don't do any data manipulation on the database if you are aiming just to redirect to a page simply redirect using javascript code like
window.location.href = '/Controller/Action/'
Ok I am convinced you have done some work on the void method, If you redirect page on the void method ajax request fails and you are not redirected to another page. For it to work you simply remove the line of code
Response.Redirect("url", false);
from controller and write a line of code as follows inside success function of ajax .
window.location.href = '/Controller/Action/'

Retrieving Json Object from action method in ASP.NET

I have searched and seen many solutions but yet I still am not getting any progress. I get no errors within the console and get nothing in return from the ajax request.
Here is action method code:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
And here is my ajax call within my controller:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
I do also have the ng directives on the desired page:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
I tested to see if the scripts work fine by assigning $scope.employees = "Hello..."; and no problems, so I know it has nothing to do with script loading.... What could be the issue? I've made sure to describe the request as GET and to return a JSON object. Am I missing something?
Thanks in advance.
EDIT
I checked the firefox console and got back Parsing Error: No XML found at location.......
Which I found odd since the server returns a JSON object, so I replaced the ajax method with the following:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
Now response is html data of the page that called it (Index), instead of the JSON object ! I assume something is happening in between the communication as suggested in this post.
As you use JQuery to fetch data from server instead of $http service and moreover success function is executed asynchronous, AngularJS will not reflect any changes that was happened, to force it, just wrap assigning into $apply:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}
Found out the issue, it's a simple mistake on my part. I was calling http://localhost:53729/AWEmployees/Index/GetEmployees which was the wrong thing to do. I took out the Index page, so now the url looks like http://localhost:53729/AWEmployees/GetEmployees and it worked perfectly!

Return view after using ajax call

I am doing a search for a date in the database using ajax to call the function. The problem is that it gives me a 404 result when it should be showing it and the ajax enters in error mode.
controller code that works
[HttpPost]
public ActionResult SearchDate(DateTime date)
{
code...
return View(employees);
}
ajax code
function SearchByDate()
{
var x = document.getElementById("DateInputField");
if (x.value != "")
{
$.ajax({
url: '/Employees/SearchDate',
type: 'GET',
data: { "date": x.value },
error: function (data) {
alert('Error!');
},
succes: function (data)
{
alert('Succes!');
}
});
}
else
{
alert('Date not selected!')
}
}
I ran the program with breakpoints and it exits with the right result but it is showing none and in the developer console i get ERROR 404!Not found! and also the ajax returns alert error.Please help! Ty
Update after some issues where fixed i get this error:
The view 'SearchDate' or its master was not found or no view engine supports the searched locations!
There are multiple errors:
[HttpPost] at backend and you are sending a GET request.
404 means file is not found, so your path might be not correct.
succes callback should be success.
contentType is not set instead you can look into traditional:true,.
Use Query string in place of send data from data parameter.
changed type: 'GET',datatype: "html", then created a partial view rendered it inside and changed the function in controller to HTTPGET and returned partial view as result!

Call PHP function in particular class via Ajax

I am using Zend Framework.
I have PHP class as:
FileName : AdminController.php
Path : /admin/AdminController.php
Ajax Function :
function exportToExcel()
{
$.ajax({
url: "/admin/AdminController/testFunction",
type: "POST",
success: function(output){
alert("Sucess "+output);
}
});
}
PHP Class:
class AdminController extends AbstractActionController
{
public function testFunction()
{
return 'Its a test!!!';
}
}
But i am not getting alert in sucess as:
Sucess Its a test!!!
What can be mistake?
How to call php function in particular phpclass/file???
try
class AdminController extends AbstractActionController
{
public function testFunction()
{
echo 'Its a test!!!';
}
}
when you do 'return' the function returns the object, this is how you return data from models to your controllers, but when you need to send data to the client, here using AJAX, you need to print the data.
UPDATE
try to open the url in browser, i.e. go to http://www.your.domain.com/admin/AdminController/testFunction and if the server is configerd as it should, you should see Its a test!!! on your screen.
if you don't see it, follow this guide to configure your server, especially the part about 'Create Route'
Try with full url in ajax call
url: "http://example.com/admin/AdminController/testFunction",
Make sure you have setup routes for this.
Must be send back a output with echo , print or any printing method
public function testFunction() {
echo 'Its a test!!!';
}
For more error check your browser console for errors

Categories