Failed to call action method using Ajax - ajax

Here's my JS (jQuery and Ajax) code:
$('#submitSignUp').click(function () {
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({ name: name, email: email, password: password }),
success: function () {
alert("Rgistered.");
}
})
})
and this is my action method. (It's in "Home controller"):
[HttpPost]
public JsonResult SignUp(string name, string email, string password)
{
TodoNet.Models.TodonetModel database = new TodoNet.Models.TodonetModel();
TodoNet.Models.User oUser = new TodoNet.Models.User()
{
FirstName = name,
LastName = name,
Email = email,
Password = password,
Salt = password,
IsDeleted = false,
IsOnline = false,
PhoneNumber = "09212131212",
RegisterDate = DateTime.Now,
LastLoginDate = DateTime.Now
};
database.Users.Add(oUser);
database.SaveChanges();
return new JsonResult();
}
but I don't know why it doesn't work. after clicking on the '#signUpSubmit' button, the "alert("Registered.")" will not be shown.
What am I doing wrong??
Note: without using Ajax, (by using ordinary send form data to the action method, everything works properly (It means I know that there's nothing wrong with the back-end code)

If the form submitting normally works, then your ajax should be sending form data not json.
Also, prevent the default action of the button click.
$('#submitSignUp').click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: "json",
data: $("#the_form_id").serialize(),
success: function () {
alert("Rgistered.");
}
});
});

You can also do this way.
On your submitSignUp submit your parameter as following.
var param =
{
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: 'json',
data: JSON.stringify(param),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (data) {
alert(1)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
Change your controller:
[HttpPost]
public ActionResult SignUp(string name, string email, string password)
{
//other implementation
return Json("", JsonRequestBehavior.AllowGet);
}
Hope this helps!

Try this as your ajax method -
$('#buttonID').on("click",function() {
var data=
{
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
};
$.ajax({
url: '#Url.Action("SignUp","ControllerName")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function () {
alert("success");
}
});
});

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

ajax POST int parameter in asp.net core

I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId is always 0 in the controller.
I have tried this without doing JSON.stringify(data) as well with no result.
I have also tried all the different form attribute variations.
Try to use contentType as 'application/x-www-form-urlencoded':
var data = { objId: 1 };
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody] attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.
var data = { };
data["objId"] = 1; //I just wanted to show you how you can add values to a json object
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
You create a model class
public class MyModel {
public int ObjId {get;set;}
}
Your controller should expect one of these
[HttpPost]
public JsonResult PassIntFromView([FromBody] MyModel data)
{
//DO stuff with int here
}
JSON has a preference for strings not integers. You are better off to use JSON.stringify(data) to parse to your controller, convert that to a integer in the controller, then parse the string that was returned as:
var data = { objId: 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',//asp.net - url: 'api/controllerName/controllerFunction'
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
var result = JSON.parse(data);
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Try this:
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: data,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Your controller:
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//DO stuff with int here
}
Js
var data = { "objId": 1};
$.ajax({
url: "ControllerName/PassIntFromView",
data: data,
type: "POST",
dataType: 'JSON',
success: function(data.result!=null) {
console.log(data.result);
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
I got it working like this
let numberFour = JSON.stringify(4);
$.ajax({
.......
.......
data: numberFour,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
......
........
});

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Ajax Post in mvc returns error all the time

I fairly new to Ajax post, and I wonder if someone could help me with why i keep getting the error message.
VideoController
[HttpPost]
public ActionResult Check(string userid, string streamid)
{
return Json(new { success = true });
}
The reason why the httppost is fairly empty yet is just to test if it works before i start writing the code.
Jquery
var userID = '#User.Identity.GetUserId()';
var defaultContext = window.location.hash === "" ? XSockets.Utils.guid() : window.location.hash.substr(1);
//alert(defaultContext);
$.ajax({
url: '/video/check',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function (error) {
alert(error.status);
}
});
I keep getting throw into my error: function and if I debug I never hit the [httpPost] Method
Can someone help
Update
I get a 404 in the alert.
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Try not to hardcore the URL:
var tURL = '#Url.Action("Check", "Video")';
$.ajax({
url: tURL ,
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
Server:
[HttpPost]
public JsonResult Foo(string userid, string streamid)
{
return new JsonResult{ Data = new {success = true}};
}
Client:
$.post('/home/foo',{userid:'123', streamid:'bar'}, function(r) {
console.log(r);
});
EDIT - If you prefer the $.ajax way instead of $.post:
$.ajax({
url: '/home/foo',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: '123',
streamid: 'bar'
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
The confusing thing is that you mix XSockets.NET with AJAX... When you have XSockets in there, why pass anything over HTTP with AJAX? You can just as easy pass it to XSockets and call your service layer from there. Just a friendly pointer.

Parameter is not passing by ajax call

I have an ajax call to a function in my controller. I need to pass a parameter to that function but it is not happening. My ajax call:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});
The function in my controller:
public PartialViewResult ListerIncidentsHotline( int page = 1)
{
int NextPage = 1 + page;
const int PageSize = 10;
int NumDossier = StructureData.DonneNumDossier((string)Session["Utilisateur"], (string)Session["MotDePasse"]);
IEnumerable<IncidentHotline> ListeIncidents = StructureData.DonneIncidentsHotline(NumDossier);
int NbreIncidents = StructureData.DonneNombreIncidents(NumDossier);
ViewBag.NombreIncidents = NbreIncidents;
var viewModel = new IncidentsPageInfo()
{
NumPages = (int)Math.Ceiling((double)ListeIncidents.Count() / PageSize),
CurrentPage = NextPage,
PageSize = PageSize,
Incidents = ListeIncidents.Skip((NextPage - 1) * PageSize).Take(PageSize),
};
return this.PartialView(viewModel);
}
When I make an alert of the variable CurrentPage, it shows me the right value, but when it comes to the ajax call, i get an error saying that the parameter is null. Can't figure out what's wrong with that.
well as a data you need to pass a numerable value with the name of page, change your ajax data
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
change data to data: {page: CurrentPage}
This is much easier....
$.get("/Accueil/ListerIncidentsHotline", { CurrentPage: #Model.CurrentPage } ).
done(function (data) {
$("#Affichage").html(data);
});
Obviously the problem came out of my ajax call. So I have to concatenate the name of the parameter with its value inside the method JSON.Stringify, as below:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
alert(CurrentPage);
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify({ page: CurrentPage }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});

Resources