So I've got these cards, a user can click the delete button to remove a card. The card has an ID which deletes the card ID or community_id and user_id from the table. When the clicks the delete button, it sends an ajax delete request to the resource controller (delete method) which does delete the row from the database... sometimes.
It's very strange, sometimes it works, other times it returns a 405 (Method Not Allowed Exception).
Here's the code:
View:
#foreach($communities as $community)
<div class="col-md-3">
<div class="card communityCard">
<div class="loadingCard" loading>
<i class="loadingSpinner fas fa-circle-notch fa-spin"></i>
</div>
<div class="commandPanel">
<div class="commandPanelInterior">
#if($community->banned == 1)
#php($community->description = "This community has been removed for violating our terms of service.")
#else
<form class="form" action="/cad" method="GET">
#csrf
<input name="community_id" type="hidden" value="{{$community->id}}">
<button type="submit" class="sideMenuButton hvr-grow btn-primary"><i class="fas fa-door-open"></i></button>
</form>
#endif
#if($community->owner_id != Auth::user()->id)
<button id="deleteCommunity{{$community->id}}" value="{{$community->id}}" type="submit" class="deleteCommunityButton sideMenuButton hvr-grow btn-danger"><i class="fas fa-trash"></i></button>
#endif
</div>
</div>
<div class="card-header">
<img class="communityIcon" src="/images/communityIcons/{{$community->icon_path}}">
<span class="communityName">{{$community->name}}</span>
</div>
<div class="card-body">
<span class="communityDescription">{{$community->description}}</span>
</div>
#if($community->banned == 0)
<div class="card-footer">
<span class="badge badge-light"><i class="fas fa-users"></i> {{$community->user_count}}</span>
#php($communityBadges = $community->badge_types)
#foreach($communityBadges as $badgeType)
<span class="badge badge-primary" title="{{$badgeType->name}}">{!!$badgeType->badge_icon!!}</span>
#endforeach
</div>
#endif
</div>
</div>
#endforeach
Javascript:
// Remove User From Community Ajax
$('.deleteCommunityButton').click(function(event){
var clickedBtn = "#" + (event.target.id);
var community_id = $(event.target).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
cache: false,
url: '/communitymembers/'+community_id,
data: {
"id": community_id,
"_method": 'DELETE'
},
success: function(response) {
$(clickedBtn).parent().parent().parent().parent().remove();
}
});
});
Controller:
public function destroy($id)
{
$memberList = CommunityMemberList::where('user_id', Auth::user()->id)->where('community_id', $id)->first();
$memberList->delete();
return redirect('/home')->with('message', 'The community has been successfully removed from your account');;
}
Web.php File:
Route::get('/home', 'HomeController#index')->name('home');
Error (From Console):
"message": "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.",
Thanks :)
Related
I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code
EmployeeViewModel
public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
Employee/ _AddEmployeeModalPartial
#model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
#Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
EmployeeController.cs
[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
site.js
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
When I click the save button on the model, the console.log(sendViewModel) returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.
1.Remove the #Html.AntiForgeryToken() inside your form,like below:
<form action="Add" >
#Html.AntiForgeryToken()
....
Then after you serialize the form you can get the AntiForgeryToken, like below:
Because when you don't add #Html.AntiForgeryToken()inside form, after you serialize the form you don't get the AntiForgeryToken, like below:
Besides, if you use <form asp-action="Add" > In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add #Html.AntiForgeryToken(),you can find in the below :
2.change your ajax like below:
$.ajax({
type: 'POST',
url:'/Employee/Add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: sendViewModel,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
result:
First, I had to change the form action from "Add" to "Employee/Add". ThenI had to remove the antiforgery token from my post action. The first code that is commented out actually works fine otherwise. In my defense I did remove the antiforgery token when I had the wrong URL, but I forgot to retest that when I had the correct one.
This is follow up question on this (Bootstrap Modal Confirmation using ASP.Net MVC and a table)
Using MVC .NetCore, I populate a "partial" view and a Table (called _Match_StatsViewAll.cshtml under a directory of the same name of my controller Match_Stats).
It's being called from an Indexview:
public async Task<ViewResult> Match_StatsIndex(string message, string comp_id, string match_id, string team_id)//ACTION METHOD/View Results
Within that table (code below) , a list of records. Each row have a button to edit or delete. To delete a record, I need to have 4 IDs since the PK is made of those 4 keys. I was able to make it work with a javascript, however, I did not like the "confirm" display being produced. Thanks to this post, I was able to add a modal for each rows in the table and delete the record. However now, If I use the original json call to refresh the partial model (that only refresh the table), I have this screen:
Here is a Row being populated from my Model:
<td>
<div>
#{i++; }
<a onclick="showInPopup('#Url.Action("Match_StatsCreateOrEdit","Match_Stats",new {comp_id=item.Match_Stats.Comp_Id, team_id=item.Match_Stats.Team_Id,match_id=item.Match_Stats.Match_Id, match_Stat_Id=item.Match_Stats.Match_Stat_Id},Context.Request.Scheme)','Update A Stat')" class="btn btn-primary btn-xs"><i class="fas fa-pencil-alt"></i> Edit</a>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete</button>
</form>
#*//add the button to launch the modal*#
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal-removeplayers_#i"><i class="fas fa-trash"></i> Delete modal</button>
<div class="modal fade" id="modal-removeplayers_#i">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation needed</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this record ?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" onsubmit="return jQueryAjaxDeleteDirect(this)" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete Json</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
In my controller - calling the delete :
public async Task<IActionResult> Match_StatsDelete(string comp_id, string team_id, string match_id, string match_stat_id)
{
// Wrap the code in a try/catch block
try
{
var deleteok = _match_statsRepository.Delete(entity);
if (deleteok != null)
{
//Code Here to populate my table only since this is a partial view inside a page
return Json(new { isValid = true, html = JavaScriptConvert.RenderRazorViewToString(this, "_Match_StatsViewAll", myPartialmodelpopulated) });
}
else
{
ModelState.AddModelError("", "Could not Delete Match");
return RedirectToAction("MatchIndex", new { message = "Success", comp_id });
}
}
catch (Exception ex)
{
// Log the exception to a file.We discussed logging to a file
//......More code here for the log has been removed //
return View("Error");
}
}
Here is the Javascript:
jQueryAjaxDeleteDirect = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
$('#view-all').html(res.html);
$.notify('Deleted Successfully !', {
globalPostion: 'Top Center',
className: 'success'
});
},
error: function (err) {
console.log(err)
}
})
} catch (ex) {
console.log(ex)
}
//prevent default form submit event
return false;
}
The " return Json" call works fine if I use the original code (so no MODAL form - just the javascript "confirm") .
Thank you for the help!
Button Click search prefect Working Only Error For Search By Enter Key
Only For NoRecord Result Otherwise Working Correctly
if i search No record result it working once again even i try to correct record does not work hide the popup form & submitted successful mgs display.
This Is the Enter Key Function
$("#app-search").keyup(function (event) {
if (event.keyCode == 13) {
$(".search-pool").click();
}
});
<div class="modal-body">
<div class="row">
<div class="col-md-4 pull-right" id="search-view">
<div class="input-group">
#Html.TextBoxFor(m => m.search, new { id = "app-search", #class = "form-control"})
<a id="btn-clear-search2" class="fa fa-times-circle-o"></a>
<span class="input-group-btn">
<button class="search-pool btn btn-primary" type="button">
<span class="fa fa-search"></span>
</button>
</span>
</div>
</div>
</div>
This is the Button Click Function
$('.search-pool').on('click', function () {
$('#label-error').hide();
$.ajax({
url: '#Url.Action("PoolDetails")',
type: 'GET',
dataType: 'html',
data: { search: $('#app-search').val() }
})
.done(function (responce) {
$('#pool-details').html(responce);
$('#btn-clear-search2').show();
checkSelected();
FillSelected();
})
});
I am coding a website from 0 to 100 Now I'm coding the Login section.
This Is My HTML Code :
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
<form class="login100-form validate-form">
<span class="login100-form-title p-b-49">
ورود
</span>
<div class="wrap-input100 validate-input m-b-23 text-right">
<span class="label-input100">ایمیل / شماره موبایل</span>
<input class="input100" type="email" id="UserEmailLogin" placeholder="ایمیل / شماره موبایل">
<span class="focus-input100" data-symbol=""></span>
</div>
<div class="wrap-input100 validate-input text-right">
<span class="label-input100">رمز عبور</span>
<input class="input100" type="password" id="UserPasswordLogin" placeholder="رمز عبور خود را وارد کنید">
<span class="focus-input100" data-symbol=""></span>
</div>
<div class="modal fade" id="MessageModalLogin" tabindex="-1" role="dialog" aria-labelledby="MessageModalLoginLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MessageModalLoginLabel">پیغام سیستمی</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-right">
<p id="ModalMessageBodyLogin"></p>
<p id="EmailSendMessageLogin"></p>
</div>
<div class="modal-footer" id="ModalFooterActiveLogin">
</div>
</div>
</div>
</div>
<div class="text-right p-t-8 p-b-31">
<a href="#">
رمز عبور خود را فراموش کرده اید ؟
</a>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn" type="button" onclick="Login()" data-toggle="modal" data-target="#MessageModalLogin">
ورود
</button>
</div>
</div>
<div class="flex-col-c p-t-70">
<span class="txt1 p-b-17">
اکانت ندارید ؟
</span>
<a href="#Url.Action("Register","Home")" class="txt2">
ثبت نام
</a>
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<script src="~/Assets/LoginRegister/js/main.js"></script>
<script src="~/Assets/js/Ajax/UserLoginRegister.js"></script>
HTML tags run correctly and there is no problem with this.
I get username and password from the user and check it in the database, Whether this username exists or not?
I've done this with AJAX
This is My JavaScript Code :
Note : Do not pay attention to the Add function , This function is for Registration page
function Add() {
var userEmail = $('#UserEmail').val();
var userMobile = $('#UserMobile').val();
var userPassword = $('#UserPassword').val();
var url = "UserRegister";
$.post(url, { email: userEmail, mobile: userMobile, password: userPassword }, function (data) {
if (data.message != "ثبت نام شما به درستی انجام شد") {
$('#ModalFooterActive').hide();
$('#SmallNote').hide();
}
else {
$('#ModalFooterActive').html('<button class="btn btn-sm btn-primary" type="button" id="btnActiveEmail">ارسال ایمیل فعالسازی</button>');
$('#SmallNote').show();
}
$("#MessageModalAjax").show();
$("#ModalMessageBody").html(data.message);
$("#btnActiveEmail").click(function () {
$(this).css("display", "none");
ActiveEmail(data.userActiveEmail, userEmail);
});
});
function ActiveEmail(userActiveEmail, userEmail) {
if (userActiveEmail == null) {
return false;
}
else {
var url = "VerifyEmail";
$.post(url, { UserEmail: userEmail, UserEmailActiveCode: userActiveEmail }, function (data) {
$("#EmailSendMessage").html(data);
});
}
function Login() {
var userEmailLogin = $("#UserEmailLogin").val();
var userPasswordLogin = $("#UserPasswordLogin").val();
var MyUser = { UserValue: userEmailLogin, UserPassword: userPasswordLogin };
$.ajax({
url: "LoginDetails",
data: JSON.stringify(MyUser),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
if (data.message == "حساب کاربری شما هنوز فعال نشده است") {
$('#ModalFooterActive').html('<button class="btn btn-sm btn-primary" type="button" id="btnActiveEmail">ارسال ایمیل فعالسازی</button>');
$("#MessageModalLogin").show();
$("#ModalMessageBodyLogin").html(data.Message);
$("#btnActiveEmail").click(function () {
$(this).css("display", "none");
ActiveEmail(data.userEmailActiveCode, userEmailLogin);
});
}
else if (data.message == "ورود با موفقیت انجام شد") {
window.setTimeout(function () {
window.location.href = SetURLLogin();
}, 5000);
}
else {
$("#ModalMessageBodyLogin").html(data.Message);
}
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
In these codes, the Add function works correctly, which means JavaScript code is not bad, and Visual Studio executes it correctly.
My problem is so weird!!!
When I run the program by Breakpoint, the program works correctly and receives the information I need from the database But inside the browser console writes: Login is not defined at HTMLButtonElement.onclick.
If it does not find the Login function, how does the database bring information???!!!
Finally: My problem is that Function Login does not run correctly
Thank you
I have this jQuery function for delete row data from MySQL using Ajax. This worked with jQuery confirm, BUT I need to add Bootstrap 3 modal box confirm(YES/NO) before delete row.
function deleteBox(id){
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(1000).html('<img src="../img/select2-spinner.gif"/>');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
// Delete with slide up effect
$("#list_"+id).slideUp(600);
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
}
}
HTML :
<div class="box-body">
<ul class="todo-list ui-sortable">
<li class="list" id="list_3"> <span class="handle"><i class="fa icon-ellipsis-vertical icon-large"></i> <i class="fa icon-ellipsis-vertical icon-large"></i></span>
<span class="tools"><i alt="Delete" title="Delete" class="icon-remove-sign icon-large" onclick=deleteBox("3")></i>delete</span>
title/sedcription <span class="flash" id="flash_3"></span>
<small class="label label-success pull-right"><i class="icon-time"></i>date</small>
</li>
<li class="list" id="list_5"> <span class="handle"><i class="fa icon-ellipsis-vertical icon-large"></i> <i class="fa icon-ellipsis-vertical icon-large"></i></span>
<span class="tools"><i alt="Delete" title="Delete" class="icon-remove-sign icon-large" onclick=deleteBox("5")></i>delete</span>
title/sedcription <span class="flash" id="flash_5"></span>
<small class="label label-success pull-right"><i class="icon-time"></i>date</small>
</li>
</ul>
</div>
How do I add bootstrap 3 confirm modal box for this function?!
Demo fiddle