Submit button not posting on modal - javascript

I have a form on a bootstrap modal with two buttons. This form is tied to an action named "DeleteWidgetConfirmed" I am trying to remove a widget from the database and from the front end, the panel gets removed from the front end but does not seem to get removed from the database.
Here is my Modal
<div class="modal fade" id="deleteWidgetModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<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" id="myModalLabel">Delete widget?</h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="myModalBody">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("DeleteWidgetConfirmed", "Dashboard", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
Do you wish to delete this widget?
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" value="DeleteWidgetConfirmed" class="btn btn-danger btn-ok" id="delete-widget">Delete</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
Here is my action:
// POST: DashboardModels/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DashboardModel dashboardModel = db.dashboards.Find(id);
db.dashboards.Remove(dashboardModel);
db.SaveChanges();
return new EmptyResult();
}
From my javascript I get the ID from the panel and store it into a variable, I then get the action attribute from my form and append the ID to the action attribute.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//we make an ajax call to the controller on click
$.ajax({
url: '#Html.Raw(Url.Action("Dashboard", "DeleteWidgetConfirmed"))',
data: { id: widgetID},
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (response) {
}
})
}
})
});
I have a hunch that maybe within my javascript I have overridden the default behaviour of the event.
What I want to achieve ultimately is
within the onclick event for the button to remove the panels(which works)
remove the entry within the database related to that panel.
When executing the post method do not refresh.

Try using AJAX to asynchronously post to your controller:
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('toggle');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
$.ajax({
url: '/Dashboard/DeleteWidgetConfirmed/',
type: 'POST',
data: { id: widgetid },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
// request failed, handle here!
},
success: function (result) {
// request succeeded! handle that here. close the modal? remove the item from the UI?
}
});
}
});
});
How you handle the success callback depends on the UI, you can use the data- attributes to do so quite easily.
You need to decorate your action method as POST if you do this:
[HttpPost]
public ActionResult DeleteWidgetConfirmed(int id) {
...
}

Related

showDialogPopup Refresh Page after Click

I have a dialog box which displays an OK button once the process completes.
I would like to refresh the page once user clicks OK.
However, in my existing code, there isn't a code to handle the behaviour after clicking OK.
Below is my current code
$.ajax({
type: "POST",
url: wsurl + "BackendRequest",
data: '{ sDomain : "' + domain + '", sUserName : "' + username '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
document.getElementById('btnGenerate').disabled = true;
showDialogPopup('Generate Request', data.d);
//window.location.reload();
},
error: function (objXMLHttpRequest, textStatus, errorThrown) {
showDialogPopup('Generate Request', data.d);
//window.location.reload();
}
});
The current window.location.reload(); refreshes the page immediately.
Is there a way to refresh the page only after user clicks OK in the showDialogPopup method?
You should write an onclick event for your "Ok" button.
try the code below:
<a onclick="OpenModal()">Open Modal</a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<button onclick="ReloadPage()">Ok</button>
</div>
</div>
</div>
<script>
//Opens the popup
function OpenModal() {
$("#myModal").modal('show');
}
//Reloads the page
function ReloadPage() {
window.location.reload();
}
You can use confirm popup modal with return type boolean
success: function (data) {
const isConfirmed = confirm('Generate Request');
if(isConfirmed) {
console.log('Ok button clicked', data.d)
window.location.reload();
}
}

jquery - how to prevent submit form continuously

I have a form in modal as follows:
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<form id="Myform" action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="button" onclick="submitform()" value="Submit">
</form>
</div>
</div>
</div>
Javascript
function submitform() {
//try
//event.stopImmediatePropagation();
//event.stopPropagation();
//check validate is valid
if (formValid) {
$("#Myform").trigger("submit");
}
}
$("#Myform").submit(function (e) {
e.preventDefault();
// e.stopImmediatePropagation();
$.ajax({
type: this.method,
cache: false,
url: this.action,
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
$('#create-media').modal('toggle');
}
},
error: function (error) {
console.log(error);
}
});
});
Currently, when the user click on the submit button, the data will be sent to the server to process, during the time waiting for the results returned, the modal has not been closed, the user can click to submit more times. I do not want this to happen.
I want to prevent users submitting continuously, do not allow users to click on the second submit button, the user must wait for the results returned, if successful, the modal will be closed.
I was thinking of disabling the submit button, but that's not safe, because the user can enable that button because of javascript on the user machine.
I tried using event.stoppropagation () and event.stopimmediatepropagation () but it did not work.
Am I doing something wrong? How do I prevent users from submitting continuously?
Thanks AlL
Follwing CertainPerformance idea, I would suggest you use a variable. However, instead of placing the variable at the beginning of the code, I would suggest to use the beforeSend callback provided by Ajax, it will be called right before sending the request.
var isBusy = false;
$("#Myform").submit(function (e) {
e.preventDefault();
if(isBusy) {
return;
}
$.ajax({
type: this.method,
cache: false,
url: this.action,
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
beforeSend: function(xhr) {
isBusy = true;
},
success: function (data) {
$('#create-media').modal('toggle');
isBusy = false;
},
error: function (error) {
console.log(error);
isBusy = false;
}
});
});
You can learn more about the beforeSend callback here
P.S. You could also use the $.ajax.active variable, which returns the amount of active ajax request, this might be a more elegent method.
Give your submitform function a persistent alreadySubmitted variable. Also, try attaching the button handler from Javascript instead of HTML, and preventDefault:
const submitform = (() => {
let alreadySubmitted = false;
return (e) => {
e.preventDefault();
if (alreadySubmitted) return;
alreadySubmitted = true;
if (formValid) {
$("#Myform").trigger("submit");
}
}
})();
document.querySelector('#Myform input[type="button"]').addEventListener('click', submitForm);

Bootstrap modal not working on loop scenarios

I am trying to create generalised method for ajax in my javascript and bootstrap modal is not working as expected.
HTML :
<div class="modal fade" id="consult_modal_v2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div style="background-color: #dc3d3e;color: #fff;height:85px !important;;" class="modal-header">
<div>
<div class="row">
<div class="col-md-11">
<h4 id="message_v2" style="text-align:center;margin-top: 10px;"></h4>
</div>
</div>
</div>
<button id="con_close1_v2" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
</div>
<div class="container"></div>
<div class="modal-body">
<div class="col-md-12" style="margin-top:3%;margin-bottom:2%;">
<div class="col-md-3" id="con_uname_v2" style="margin-top:11px">Admin Username</div>
<div class="col-md-9"><input type="text" id="con_sect_name_v2" class="form-control"></div>
<div class="col-md-3" id="con_pass_v2" style="margin-top:11px">Admin Password</div>
<div class="col-md-9"><input type="password" id="con_sect_pass_v2" class="form-control"></div>
</div>
</div>
<div style="border:none;" class="modal-footer" >
<button class="btn btn-default" id="con_close_v2" style="margin-top:3%;">Cancel</button>
<button class="btn btn-default" id="con_sect_ok_v2" style="margin-right:2%;margin-top:3%;">Override</button>
<button class="btn btn-default" id="con_upd_sect_ok_v2" style="display:none;margin-right:2%;margin-top:3%;">Override</button>
</div>
</div>
</div>
</div>
JavaScript:
Executed as
generalised_ajax('post_url',
{
'sub_id': sub_id,
'status': status,
'_token': csrf_token
}, "POST", function () {
console.log('success placing apt');
}, {},
function () {
console.log('apt cancelled');
}, {});
function generalised_ajax(url, data, type, post_success, post_success_params, post_cancel, post_cancel_params) {
$.ajax({
url: url,
data: data,
type: type,
headers: {Accept: "application/json"},
dataType: 'json',
success: function (result, status, xhr) {
post_success(post_success_params);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.type === "confirmation") {
responseProcess = xhr.responseJSON;
generalised_confirm(responseProcess.message, {
url: url,
data: data,
type: type,
post_success: post_success,
post_success_params: post_success_params,
post_cancel: post_cancel,
post_cancel_params: post_cancel_params
}, responseProcess.config_name);
} else if(xhr.responseJSON.type === "admin_auth"){
generalised_authentication(responseProcess.message, {
url: url,
data: data,
type: type,
post_success: post_success,
post_success_params: post_success_params,
post_cancel: post_cancel,
post_cancel_params: post_cancel_params
});
}
}
});
}
function generalised_confirm(message, data, config_name) {
var r = confirm(message);
if (r === true) {
data.data[config_name] = true;
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
} else {
data.post_cancel(data.post_cancel_params);
}
}
var modelX = $("#consult_modal_v2");
function generalised_authentication(message, data){
var uname = $("#con_sect_name_v2");
var pass = $("#con_sect_pass_v2");
$("#message_v2").val(message);
modelX.modal('toggle');
$("#con_sect_ok_v2").click(function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
$("#con_close_v2").click(function(event){
modelX.modal('toggle');
data.post_cancel(data.post_cancel_params);
});
}
Expected scenarios:
Sent ajax
Server responded with admin_auth error
Open modal
Input admin creds (wrong ones)
Close modal
Sent ajax
Server responded with admin_auth error
Repeat from stage 3
How it's working right now
Sent ajax
Server responded with admin_auth error
Open modal
Input admin creds (wrong ones)
Close modal
Sent ajax
Now server responded with same ajax as Point 2. But modal won't open again.
It is working fine with javascripts confirmation popup.
Update:
After I removed fade class from modal, it started appearing everytime. But now it sends double of ajax of previous attempt.
Like for first time once, second time twice, third time 4 times, 4th time 8 times and so on.
I don't know what is the reason of this behaviour but
changing
$("#con_sect_ok_v2").click(function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
to
$("#con_sect_ok_v2").one('click',function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
solved it.
Credits https://stackoverflow.com/a/3393694/2598994

Insert data to db using store method of resource controller with ajax call

In my laravel project i am inserting data through the resource controller .but now I want to insertion using ajax request with same route and same method of resource controller how i have send the url and how to send the form data to it.
route
Route::resource('/makes', 'MakeController');
controller
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
//----models--------
use App\Make;
class Makecontroller extends Controller
{
public function index()
{
return View("pagination_common.index");
}
public function create()
{
}
public function store(Request $request)
{
$input['name'] = Input::get('name');
$rules = array('name' => "unique:makes,name");
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Redirect::back()->with('alert-danger',"Make Name already exist.")->withInput();
}
else{
$make = new Make();
$make_detail = $make->add_make($request);
$data['name'] = $request->name;
$make = make::find($make_detail['id']);
activity('create')->performedOn($make)->log('');
return redirect('/makes')->with('alert-success', 'Make Created successfully.');
}
}
public function show($id)
{
}
public function edit($id)
{
}
public function update(Request $req, $id)
{
}
public function destroy($id)
{
}
}
model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;
use DB;
class Make extends Model
{
use SoftDeletes;
public function add_make($req)
{
$this->name = $req['name'];
$this->save();
return ['id' => $this->id];
}
public function edit_make($req,$id)
{
$make = $this->find($id);
$make->name = $req->name;
$make->save();
}
public function make_detail($id)
{
$client = DB::select('select * from makes WHERE id=:id',['id'=>$id]);
return $client;
}
}
Add form div
<div class="modal" id="add_item">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Make</h4>
</div>
{{ Form::open(array('class' => 'form-horizontal form-validate-jquery','id' => 'add_item_form')) }}
{{ Form:: hidden('model', "make","" ) }}
<div class="modal-body">
<fieldset class="content-group">
<legend class="text-bold"></legend>
<div class="form-group">
<label class="control-label col-lg-3">Name: <span class="text-danger">*</span></label>
<div class="col-lg-9">{{ Form:: text('name', null, array('class' => 'form-control', 'required' => '','placeholder' => 'name', 'maxlength' => '50')) }}</div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-primary" id="item-add-btn" data-resource="faq" onclick="add_item_common('make','Make')" >Submit</button>
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Cancel</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
js code of ajax function
function add_item_common(model,item)
{
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var objectResult = $('#add_item_form').serializeArray();
$.ajax({
type: "POST",
url: "makes",
dataType: 'json',
data: {
_token: CSRF_TOKEN,
fields: objectResult
},
success: function (data) {
console.log(data);
if(data=='success')
{
var page = $(".pagination .active span").html();
ajaxLoad('{{Request::segment(1)}}?page='+page);
$('#delete_confirm').modal('hide');
var add_success = '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>'+model+' '+item+' added successfully.</div>';
$(".content").prepend(add_success);
setTimeout(function(){ $(".alert-success").remove(); }, 5000);
}
}
});
}
remove dataType: 'json', and change data to data:$("#add_item_form").serialize()
That should do it.
Replace your ajax code with following.
$.ajax({
type: "POST",
url: "makes",
data:$("#add_item_form").serialize(),
success: function (data) {
console.log(data);
}
});

MVC4 client side validation and ajax

Answer:
OK answer supplied below, by #www.innovacall.com is correct, I just didn't read it right the first time, now it works perfectly, thanks.
Original question:
I tried some solutions but none works for me.
In my project, I got a modal popup like this (I use bootstrap):
<!-- Modal -->
<div class="modal fade" id="skillAnswerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">#ViewBag.AddressTimeTableMapModalEditHeaderTitle</h4>
</div>
<div class="modal-body">
<div id="addSkillAnswerModal">
#Html.Partial("_AddSkillAnswer", Model.TempSkillAnswer)
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">#ViewBag.CloseButtonLabel</button>
<button type="button" class="btn btn-primary" id="btnAddSkillAnswerModal" >#ViewBag.SaveChangesButtonLabel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I submit data from that popup with the following ajax:
$("#btnAddSkillAnswerModal").click(function () {
$.ajax({
url: addSkillUrl,
type: "POST",
cache: false,
async: true,
traditional: true,
data: $("#addSkillAnswerModal :input").serialize(),
dataType: "json",
success: function (result) {
$("#skillAnswerModal").modal('toggle');
$("#addSkillAnswerModal input[type!=hidden]").val('');
$("#IsAnswerVisible").val("true");
oTable.fnReloadAjax();
}
});
});
The problem:
Standard #Html.ValidationSummary() helper inside the View rendered in my modal popup, is not being called - thus I have no client side validation. I know that #Html.ValidationSummary() only works when I use #Html.BeginForm(...) but how can I validate my ajax before submit? I tried something like this:
$("#btnAddSkillAnswerModal").click(function () {
$("#AddSkillAnswerForm").validate({
debug: true,
submitHandler: function (form) {
$.ajax({
url: addSkillUrl,
type: "POST",
cache: false,
async: true,
traditional: true,
data: $("#addSkillAnswerModal :input").serialize(),
dataType: "json",
success: function (result) {
$("#skillAnswerModal").modal('toggle');
$("#addSkillAnswerModal input[type!=hidden]").val('');
$("#IsAnswerVisible").val("true");
oTable.fnReloadAjax();
}
});
},
showErrors: function (errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
});
But it's not working, that is: there are no errors, but when I debug the JS, it sort of "skips" the validation, neither submitHandler nor showErrors is being hit...
How can I validate my form before ajax call?
Best regards.
EDIT1:
#www.innovacall.com:
I tried this approach but still it is not working for some reason...
My _AddSkillAnswer partial looks like this:
#model HostessServiceApplication.WebUI.Models.Admin.AgencyAnimatorSkillAnswerListAddSkillAnswer
#using HostessServiceApplication.Common.Localizer
#using HostessServiceApplication.WebUI.Resources
#using HostessServiceApplication.WebUI.Resources.Admin
#{
Layout = null;
//GlobalResources:
var globalLocalizer = new UniversalTextLocalizer(typeof(TranslationStrings));
ViewBag.SaveChangesButtonLabel = globalLocalizer.GetTranslatedVariable("SaveChangesButtonLabel");
var viewSpecificLocalizer = new UniversalTextLocalizer(typeof(AddSkillAnswer));
ViewBag.Title = viewSpecificLocalizer.GetTranslatedVariable("AddSkillAnswerPageTitle");
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm("AddSkillAnswer", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" ,id="AddSkillAnswerForm"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#Html.EditorForModel("Admin/AgencyAnimatorSkillAnswerListAddSkillAnswer")
}
I tried the following combinations:
$("#btnAddSkillAnswerModal").click(function () {
var form = $("#AddSkillAnswerForm");
$.validator.unobtrusive.parse(form);
//form.validate();
form.validate({
debug: true,
submitHandler: function (form) {
$.ajax({
url: addSkillUrl,
type: "POST",
cache: false,
async: true,
traditional: true,
data: $("#addSkillAnswerModal :input").serialize(),
dataType: "json",
success: function (result) {
$("#skillAnswerModal").modal('toggle');
$("#addSkillAnswerModal input[type!=hidden]").val('');
$("#IsAnswerVisible").val("true");
oTable.fnReloadAjax();
}
});
},
showErrors: function (errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
});
and this:
$("#btnAddSkillAnswerModal").click(function () {
var form = $("#AddSkillAnswerForm")
.removeData("validator") /* added by the raw jquery.validate plugin */
.removeData("unobtrusiveValidation"); /* added by the jquery unobtrusive plugin */
$.validator.unobtrusive.parse(form);
form.validate({
debug: true,
submitHandler: function (form) {
$.ajax({
url: addSkillUrl,
type: "POST",
cache: false,
async: true,
traditional: true,
data: $("#addSkillAnswerModal :input").serialize(),
dataType: "json",
success: function (result) {
$("#skillAnswerModal").modal('toggle');
$("#addSkillAnswerModal input[type!=hidden]").val('');
$("#IsAnswerVisible").val("true");
oTable.fnReloadAjax();
}
});
},
showErrors: function (errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
});
but still it doesn't work, neither submitHandler nor showErrors is being hit.
If you loaded your form with ajax, you need to parse your form again :
$.validator.unobtrusive.parse(form);
form.validate();
if (form.valid()) {
form.submit();
}

Categories

Resources