I got the following problem.
in my Controller, this method is supposed to return a JSON with the pets from the database. but is being called, the server returns a 404.
public async Task<JsonResult> GetPetsAsync(int ownerId )
{
var pets = await _dataContext.Pets
.Where(p => p.Owner.Id == ownerId)
.OrderBy(p => p.Name)
.ToListAsync();
return Json(pets);
}
=====================================================
This is the form that provides the OwnerId for the method to find the pets for that particular owner.
<div class="row m-auto align-content-center">
<div class="col-md-4">
<form asp-action="Assign" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="OwnerId" class="form-label fw-bold"></label>
<select asp-for="OwnerId" asp-items="Model.Owners" class="form-control"></select>
<span asp-validation-for="OwnerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PetId" class="form-label fw-bold"></label>
<select asp-for="PetId" asp-items="Model.Pets" class="form-control"></select>
<span asp-validation-for="PetId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="form-label fw-bold "></label>
<textarea asp-for="Remarks" class="form-control"></textarea>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<button value="Assign" type="submit" class="btn btn-primary btn-sm"><i class="bi bi-calendar-plus-fill"></i></button>
<a asp-action="Index" class="btn btn-success btn-sm"><i class="bi bi-arrow-return-left"></i> Go Back</a>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
</form>
</div>
</div>
In my View -- the AJAX request to GetPetsAsync
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$("#OwnerId").change(function () {
$("#PetId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetPetsAsync", "Agenda")',
//Take the OwnerId and send it to the JsonResult Method to retrieve the pets
data: { ownerId: $("#OwnerId").val() },
dataType: 'Json',
success: function (pets) {
$("#PetId").append('<option value="0">(Select a pet...)</option>');
$.each(pets, function (i, pet) {
$("#PetId").append('<option value="'
+ pet.id + '">'
+ pet.name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve pets. ' + ex.statusText);
}
});
return false;
})
});
</script>
It looks like this feature change is affecting you.
Async suffix for controller action names will be trimmed by default #14716
You can just drop the "Async" suffix from your view-side code. Which is why renaming your method "fixed" your problem.
You have control over this behavior in your app startup with SuppressAsyncSuffixInActionName
builder.Services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
Make sure the "httppost" attribute is used. If you continue to get an error, check the data part in the ajax section.
I found the solution. Incredibly just by changing the Method Name to GetPetAsyncronous the problem was solve. I don’t know why the previous method wouldn’t work. But It worked.
Related
**Hi I have Login and Register Page in one view.Login controller does not have view. i want to show error message when user enter wrong email and password. but it return blank page with {"Fail"} with url Account/Login
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").on("click",function () {
//collect the user data
var data = {};
data.Email = $("#Email").val();
data.Password = $("#Password").val();
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Account/Login",
type: "POST",
dataType: "json",
data: {
model: data,
__RequestVerificationToken: token,
},
success: function () {
$("#alertmessage").show()
},
})
})
})
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login </h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="submit" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string Emaillog,string Passwordlog)
{
string result = "Fail";
User appUser = _context.Users.FirstOrDefault(u => u.Email == Emaillog);
if (appUser != null)
{
if (appUser.Password ==Passwordlog)
{
Session["ActiveUser"] = appUser;
return RedirectToAction("MainAccount");
}
}
return Json(result, JsonRequestBehavior.AllowGet); }
I tried change to JsonResult action but still the same. I don't know where gone wrong. **
Your ajax call is not being called because your submit button is submitting the form and doing a redirect.
Add a event.preventDefault() button click event so that it won't do a normal synchronous POST.
// add e parameter, this is for the event
$("#logbut").on("click",function (e) {
// this is to avoid the form being submitted, and proceed with your script call
e.preventDefault();
// ...
})
I have found a bug - and I haven't found any solution to this.
I have a code in ASP.NET Core (using VSPro 2019 16.5.0):
public IActionResult CreateSubGroup(MyClass model, string returnUrl = null)
{
if (ModelState.CreateMyClassValidation())
{
if (!db.MyClass.Where(x => x.Title == model.Title).Any())
{
ViewData["ReturnUrl"] = returnUrl;
var code = new MyClass { Title = model.Title, IdGroup = model.IdGroup, GroupCode = model.GroupCode};
db.MyClass.Add(code);
var result = db.SaveChanges();
if (result > 0)//if there was no issue (at least one row was changed)
{
this.AddNotification(MessagesHandler.Success, $"Item\"{model.Title}\" was successfully created.");
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" cannot be created.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" already exists.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"ErrorMessage.");
}
return RedirectToLocal(returnUrl);
}
Creating of new Item always crashes with unique code exception from DB - During debuging I have found, that every row is executed twice (and I don't know why??) - so also the row db.SaveChanges() is executed twice and that's why I got this exception.
Second bad thing is, that not even the first attempt to save database is not executed (= new Item is not created in DB).
Have you seen this error?
EDIT:
I have found, that it happens only when data are posted from view with JS/AJAX (from modal window)
Here is the code for sending data:
<div class="modal fade" id="ModalWindow" tabindex="-1" role="dialog" aria-labelledby="ModalForm" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="ModalForm" action="" method="post" class="validator">
<div class="modal-body">
<div class="form-group">
<label asp-for="Id"></label>
<input class="form-control" asp-for="Id" value="" readonly data-val="false">
<div class="form-text text-muted small">ID cannot be changed!</div>
</div>
<div class="form-group">
<label asp-for="Title"></label>
<input class="form-control mlfb-create" asp-for="Title" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="Title"></span>
</div>
<div class="form-group">
<label asp-for="IdGroup"></label>
<select class="selectpicker form-control" asp-for="IdGroup" data-live-search="true" data-style="btn-info" tabindex="#(++tabindex)">
#if (data?.GroupData != null)
{
#foreach (var item in data?.GroupData)
{
<option value="#(item.Id)">#item.Title</option>
}
}
</select>
</div>
<div class="form-group">
<label asp-for="GroupCode"></label>
<input class="form-control mlfb-create" asp-for="GroupCode" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="GroupCode"></span>
</div>
</div>
<div class="text-center modal-footer">
<button type="submit" class="btn btn-success _modal-buttton-save" tabindex="#(++tabindex)"><i class="fas fa-check mr-2"></i><span>Save</span></button>
<button type="reset" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(function () {
"use strict";
$(document).on('click', '._createSubFormButton', function () {
$('#ModalWindow').modal('show');
$('.modal-title').text('Creating of subgroup');
$('.modal-buttton-save span').text('Create');
$('#ModalForm').attr('action', '/MyCode/CreateSubGroup/?returnurl=' + window.location.href);
});
// Edit form
$(document).on('click', 'tr ._editSubFormButton', function () {
$('#ModalWindow').modal('show');
var $tr = $(this).closest('tr');
var Id = $tr.find('._Id').text();
var Title = $tr.find('._Title').text();
var IdGroup = $tr.find('._IdGroup').text();
var GroupCode = $tr.find('._GroupCode').text();
$('.modal-title').text('Editing of subgroup');
$('#ModalForm').attr('action', '/MyCode/EditSubGroup/' + Id + '?returnurl=' + window.location.href);
$('#Id').val(Id);
$('#Title').val(Title);
$('#GroupCode').val(GroupCode);
});
// form validation reset during closing modal form
$('#ModalWindow').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
$('#IdGroup').load();
$('.form-group .is-invalid').each(function () { $(this).removeClass('is-invalid'); });
$('.form-group .is-valid').each(function () { $(this).removeClass('is-valid'); });
$('.form-text.text-danger').each(function () { $(this).removeClass('text-danger'); });
$('.form-text.text-success').each(function () { $(this).removeClass('text-success'); });
$('.invalid-feedback').each(function () { $(this).remove(); });
});
$(document).on('submit', '#ModalForm', function (e) {
var form = $('#ModalForm');
if (form.valid()) {
console.log(form.serializeArray());
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serializeArray()
}).done(function () {
console.log('done');
$tr.find('._Number').text();
var $tr = $(this).closest('tr');
})
.fail(function () {
console.log('fail');
});
$('#ModalWindow').modal('hide');
}
});
error I got:
Have you tried debugging this code? Debugging with setting breakpoints and stepping through the code would help you find what is wrong with this code.
I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());
I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});
I got a problem that's really ruining my life now. I'm trying to pass values to a codeigniter controller through Ajax.
I've read many things about it but I can't find why this is not working.
So I've made a form in a bootstrap modal windows to add a new member. The values are: first name, last name, email and passowrd.
I'm using jQuery validate to verify the infos and then I wanna pass the value to the controller.
$('#addMember form').validate({ // initialize plugin
rules: {
lname: {
required: true,
minlength: 2
},
name: {
required: true,
minlength: 2
},
mail: {
required: true,
email: true
},
password: {
required: true
},
repassword: {
required: true,
equalTo: "#password"
}
},
highlight: function (element) {
$(element).closest('.input-group')
.removeClass('success').addClass('error');
},
success: function (element) {
element.addClass('valid').closest('.input-group')
.removeClass('error').addClass('success');
},
submitHandler: function (form) {
// form validates so do the ajax
var dataString = $(form).serialize();
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: dataString,
success: function (data, status) {
// ajax done
// do whatever & close the modal
alert(status);
$('.modal').modal('hide');
}
});
return false; // ajax used, block the normal submit
}
});
<div id="addMember" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form id="addMemberForm" method="POST" action="<?php echo base_url('adminMembers/process_add_member');?>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"></span></button>
<h4 class="modal-title">Add a new member</h4>
</div>
<div class="modal-body">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Last Name</span>
<input name="lname" type="text" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">First name</span>
<input name="name" type="text" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Email</span>
<input name="mail" type="email" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Password</span>
<input id="password" name="password" type="password" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Password again</span>
<input name="repassword" type="password" class="form-control" placeholder="" aria-describedby="basic-addon1">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" value="add">Add</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I got a success message in an alert window so the ajax part is working.
Then I don't know how to use the values in my controller.
If I try to print $this->input->post('lname') I got an empty value.
Any ideas please?
EDIT: Might be useful:
My javascript code is placed right after the </div><!-- /.modal -->.
The function add_Member in my controller looks like:
public function process_add_member()
{
$this->membersManager->add_member();
}
And finally the model:
public function add_member()
{
$name = $this->input->post('name');
$lname = $this->input->post('lname');
$email = $this->input->post('mail');
$password = $this->input->post('password');
return $this->db->set(array('name' => $name,
'lname' => $lname,
'login' => $email,
'email' => $email,
'password' => $password))->insert($this->table);
}
As I said I tried to replace $this->input->post() by $_POST[] but still not working.
To finish I wanna ay that I've tried the same without using AJAX to pass the values and it is working. I need to use AJAX because I want the form to be in a bootstrap modal window.
The thing is that it seems my function process_add_Member() in the controller is not called. I can do anything in it and it won't happen.
Nobody? :( I really don't understand what is not working here.
HELP!
Is there someone that can help me please ?
Since you are passing data using the form serialize method insteading of using $this->input->post() retrieve the post value directly $_POST['<input_name>'] .
Hope this will solve your problem since.
You should use the form_open() helper function in your view, so that the CSRF token is included as a hidden field.
And in general: you should always use the helper functions and classes whenever possible. There is no use in working with a framework if you don't use the provided functions.