Javascript runtime error: 'function' is undefined - javascript

It says my function is undefined yet it is clearly defined below the body of the program's content.
<button type="button" class="btn btn-primary" data-dismiss="modal" id="CmdBranchEditOk" onclick="CmdBranchEditOk_OnClick()">
#*Add*#
function CmdBranchAdd_OnClick() {
alert('Hi');
#*$('#BranchEdit').modal({
show: true,
backdrop: false
});
document.getElementById('BranchEdit-BranchCode').value = "";
document.getElementById('BranchEdit-Branch').value = "";
document.getElementById('BranchEdit-CompanyID').value = "";*#
}
at the moment, the main body of the function has been commented out to test if it can connect to the function. but when run and pressed, it return a javarscript runtime error stating that the function in the button in undefined.
Edit #1:
Sorry, copied wrong line of code xD Forgive me
<button style="float:left" id="CmdAddBranch" type="submit" class="btn btn-default" onclick="CmdBranchAdd_OnClick()">Add A Branch</button>
while I'm at it, here are the loaded scripts - the function was originally supposed to call for a modal but It should just alert for now. But it's doesn't.
<script src="~/js/jquery.js"></script>
<script src="~/lib/bootstrap/js/bootstrap.js"></script>
<script src="~/wijmo/controls/wijmo.min.js" type="text/javascript"></script>
<script src="~/wijmo/controls/wijmo.input.min.js"></script>
<script src="~/wijmo/controls/wijmo.grid.min.js" type="text/javascript"> </script>
<script src="~/wijmo/controls/wijmo.chart.min.js"></script>
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
<link href="~/wijmo/styles/wijmo.min.css" rel="stylesheet" />
Edit #2: Here's the entire code block to see if it has any problems.
#{
ViewBag.Title = "Branch";
}
<!-- Script Linkings -->
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
<script src="~/lib/bootstrap/js/bootstrap.js"></script>
<script src="~/wijmo/controls/wijmo.min.js" type="text/javascript"></script>
<script src="~/wijmo/controls/wijmo.input.min.js"></script>
<script src="~/wijmo/controls/wijmo.grid.min.js" type="text/javascript"></script>
<script src="~/wijmo/controls/wijmo.chart.min.js"></script>
<link href="~/wijmo/styles/wijmo.min.css" rel="stylesheet" />
#*<link href="/css/bootstrap.min.css" rel="stylesheet" /> --- this S.O.B will make things white. Big "NO, NO" *#
#*List*#
<div id="DivEvents">
<div class="container">
<div class="row">
<div class="col-lg-11">
<br /><br /><br />
<h2 style="margin-bottom:5px; margin-top:5px;">Branches</h2>
<button style="float:left" id="CmdAddBranch" type="submit" class="btn btn-default" onclick="CmdBranchAdd_OnClick()">Add A Branch</button>
</div>
</div>
<br />
<div class="row">
<div class="col-lg-12">
<div id="BranchGrid" class="grid"></div>
</div>
</div>
<br />
<div class="row">
<div class="btn-group col-md-7" id="naviagtionPageEvent">
<button type="button" class="btn btn-default" id="btnMoveToFirstPageEvent">
<span class="glyphicon glyphicon-fast-backward"></span>
</button>
<button type="button" class="btn btn-default" id="btnMoveToPreviousPageEvent">
<span class="glyphicon glyphicon-step-backward"></span>
</button>
<button type="button" class="btn btn-default" disabled style="width:100px" id="btnCurrentPageEvent"></button>
<button type="button" class="btn btn-default" id="btnMoveToNextPageEvent">
<span class="glyphicon glyphicon-step-forward"></span>
</button>
<button type="button" class="btn btn-default" id="btnMoveToLastPageEvent">
<span class="glyphicon glyphicon-fast-forward"></span>
</button>
</div>
</div>
</div>
</div>
#*Edit Detail*#
<div class="modal fade" id="BranchEdit">
<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">Branch Edit</h4>
</div>
<div class="modal-body">
<dl class="dl-horizontal">
<dt>Branch Code</dt>
<dd>
<input class="form-control" id="BranchEdit-BranchCode" type="text" />
</dd>
<dt>Branch</dt>
<dd>
<input class="form-control" id="BranchEdit-Branch" type="text" />
</dd>
<dt>Company ID</dt>
<dd>
<input class="form-control" id="BranchEdit-CompanyID" type="text" />
</dd>
</dl>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="CmdBranchEditOk" onclick="CmdBranchEditOk_OnClick()">
Ok
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" id="CmdBranchEditCancel">
Cancel
</button>
</div>
</div>
</div>
</div>
#*Loading*#
<div class="modal fade" id="loading" tabindex="-1" role="dialog" aria-labelledby="Loading..." aria-hidden="true">
<div class="modal-dialog" style="width: 220px;">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Loading...</h4>
</div>
<div class="modal-body">
<img src="/img/progress_bar.gif" />
</div>
</div>
</div>
</div>
#*Module*#
<script type="text/javascript">
var Branches;
var BranchGrid;
var btnFirstPageEvent;
var btnPreviousPageEvent;
var btnNextPageEvent;
var btnLastPageEvent;
var btnCurrentPageEvent;
#*Edit*#
function CmdBranchEdit_OnClick() {
Branches.editItem(Branches.currentItem);
$('#BranchEdit').modal({
show: true,
backdrop: false
});
var Branch = Branches.currentEditItem;
document.getElementById('BranchEdit-BranchCode').value = Branch.BranchCode ? Branch.BranchCode : '';
document.getElementById('BranchEdit-Branch').value = Branch.Branch ? Branch.Branch : '';
document.getElementById('BranchEdit-CompanyID').value = Branch.CompanyID ? Branch.CompanyID : '';
}
#*Add*#
$(document).ready(function(){
function CmdBranchAdd_OnClick() {
alert('Hi');
#*$('#BranchEdit').modal({
show: true,
backdrop: false
});
document.getElementById('BranchEdit-BranchCode').value = "";
document.getElementById('BranchEdit-Branch').value = "";
document.getElementById('BranchEdit-CompanyID').value = "";*#
}
}
#*Delete*#
function CmdBranchDelete_OnClick() {
Branches.editItem(Branches.currentItem);
var Id = Branches.currentEditItem.Id;
var BranchDescription = Branches.currentEditItem.Branch;
if (confirm("Delete " + BranchDescription + "?") == true) {
$.ajax({
type: "DELETE",
url: "/api/DeleteEvent/" + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
statusCode: {
200: function () {
window.location.reload();
},
404: function () {
alert("Not found");
},
400: function () {
alert("Bad request");
}
}
});
}
}
#*Save Edit*#
function CmdBranchEditOk_OnClick() {
if (confirm("Save Event?") == true) {
var Branch = new Object();
Branch.BranchCode = document.getElementById('BranchEdit-BranchCode').value;
Branch.Branch = document.getElementById('BranchEdit-Branch').value;
Branch.CompanyID = document.getElementById('BranchEdit-CompanyID').value;
var data = JSON.stringify(Event);
// Add New
if (Branch.Id == 0) {
$.ajax({
type: "POST",
url: "/api/AddEvent",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (id) {
if (id > 0) {
window.location.reload();
} else {
alert("Not added");
}
}
});
// Edit
} else {
$.ajax({
type: "PUT",
url: "/api/UpdateEvent/" + Branch.Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
statusCode: {
200: function () {
window.location.reload();
},
404: function () {
alert("Not found");
},
400: function () {
alert("Bad request");
}
}
});
}
}
}
#*List Functions*#
function GetBranches() {
var Branches = new wijmo.collections.ObservableArray();
$('#loading').modal('show');
$.ajax({
url: '/api/Event',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (Results) {
$('#loading').modal('hide');
if (Results.length > 0) {
for (i = 0; i < Results.length; i++) {
Branches.push({
EditId: "<button class='btn btn-primary btn-xs' data-toggle='modal' id='CmdBranchEvent' onclick='CmdBranchEdit_OnClick()'>Edit</button>",
DeleteId: "<button class='btn btn-danger btn-xs' data-toggle='modal' id='CmdBranchEvent' onclick='CmdBranchDelete_OnClick()'>Delete</button>",
Id: Results[i]["Id"],
BranchCode: Results[i]["BranchCode"],
BranchDescription: Results[i]["Branch"],
CompanyID: Results[i]["CompanyID"],
});
}
} else {
alert("No data.");
}
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
}
);
return Branches;
}
#*Delete*#
function DeleteBranch(Id) {
$.ajax({
type: "DELETE",
url: "/api/DeleteEvent/" + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { Id: BranchId },
success: function (response) {
alert("Branch Deleted.");
window.location.reload();
},
failure: function (response) {
alert("Error - " + response.d);
},
error: function (e) { }
});
window.location.reload();
}
function UpdateNavigateButtonsEvent() {
if (Branches.pageSize <= 0) {
document.getElementById('naviagtionPageEvent').style.display = 'none';
return;
}
document.getElementById('naviagtionPageEvent').style.display = 'block';
if (Branches.pageIndex === 0) {
btnFirstPageEvent.setAttribute('disabled', 'disabled');
btnPreviousPageEvent.setAttribute('disabled', 'disabled');
btnNextPageEvent.removeAttribute('disabled');
btnLastPageEvent.removeAttribute('disabled');
}
else if (Branches.pageIndex === (Branches.pageCount - 1)) {
btnFirstPageEvent.removeAttribute('disabled');
btnPreviousPageEvent.removeAttribute('disabled');
btnLastPageEvent.setAttribute('disabled', 'disabled');
btnNextPageEvent.setAttribute('disabled', 'disabled');
}
else {
btnFirstPageEvent.removeAttribute('disabled');
btnPreviousPageEvent.removeAttribute('disabled');
btnNextPageEvent.removeAttribute('disabled');
btnLastPageEvent.removeAttribute('disabled');
}
btnCurrentPageEvent.innerHTML = (Branches.pageIndex + 1) + ' / ' + Branches.pageCount;
}
$(document).ready(function () {
btnFirstPageEvent = document.getElementById('btnMoveToFirstPageEvent');
btnPreviousPageEvent = document.getElementById('btnMoveToPreviousPageEvent');
btnNextPageEvent = document.getElementById('btnMoveToNextPageEvent');
btnLastPageEvent = document.getElementById('btnMoveToLastPageEvent');
btnCurrentPageEvent = document.getElementById('btnCurrentPageEvent');
Branches = new wijmo.collections.CollectionView(GetBranches());
BranchGrid = new wijmo.grid.FlexGrid('#BranchGrid');
BranchGrid.initialize({
columns: [
{
"header": "Edit",
"binding": "EditId",
"width": 60,
"allowSorting": false,
"isContentHtml": true
},
{
"header": "Delete",
"binding": "DeleteId",
"width": 60,
"allowSorting": false,
"isContentHtml": true
},
{
"header": "Branch Code",
"binding": "BranchCode",
"allowSorting": false,
"width": "4*"
},
{
"header": "Company ID",
"binding": "CompanyID",
"allowSorting": false,
"width": 80
},
{
"header": "Branch",
"binding": "BranchDescription",
"allowSorting": false,
"width": "4*"
},
],
autoGenerateColumns: false,
itemsSource: Brances,
isReadOnly: true,
selectionMode: wijmo.grid.SelectionMode.Row
});
BranchGrid.trackChanges = true;
Branches.pageSize = 15;
});
UpdateNavigateButtonsEvent();
// Page Button Events
btnFirstPageEvent.addEventListener('click', function () {
Branches.moveToFirstPage();
UpdateNavigateButtonsEvent();
});
btnPreviousPageEvent.addEventListener('click', function () {
Branches.moveToPreviousPage();
UpdateNavigateButtonsEvent();
});
btnNextPageEvent.addEventListener('click', function () {
Branches.moveToNextPage();
UpdateNavigateButtonsEvent();
});
btnLastPageEvent.addEventListener('click', function () {
Branches.moveToLastPage();
UpdateNavigateButtonsEvent();
});
});
</script>
Tried Rao's suggestion - still nothing :( This is starting to be a pain in the ass..)

You have code for a method called
CmdBranchAdd_OnClick
But the element references a function called
CmdBranchEdit_OnClick

move this line
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
to the top of other js files.
Also you have two jquery.js file included. Only choose one which is the best fixing your application.
<script src="~/js/jquery.js"></script>
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>

Few Suggestions:
Try wrapping your function inside as below
$(document).ready(function(){
function CmdBranchAdd_OnClick() {
alert('Hi');
}
});
then as #user86745458 said remove either jquery.js or jquery-latest.min.js reference and keep your js files at the top of all other links!!
Try changing type of button from submit to just button.

Related

Button not working to get data from one database and add it into new databse

I new to learn PHP,HTML,CSS and JAVASCRIPT, and battle with this code. I have tried it without and with form, but when click on button,(with form) it is running for 2 seconds and it does not update my new database. With out form nothing is happening.
I know there are problems with my code, learning and fixing them.
<?php include_once 'header.php'?>
<form id="basicForm" action="updateDatabase.php" method="post" enctype="multipart/form-data" name="basicForm">
<div class="wrapper">
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-25">
<div class="card">
<div class="card-header">
<h3 class="card-title">Update Database</h3>
</div>
<div class="card-body">
<p>
<button position="relative" class="btn btn-block btn-outline-danger btn-lg c1" id="homeDB">Home DB</button>
<span id="homeupdate"></span>
<span id="loaders1" style="display:none;">
<img alt="" src="dist/img/loader11.gif">
</span>
</p>
<p>
<button position="relative" class="btn btn-block btn-outline-success btn-lg c1" id="workdb">Work DB</button>
<span id="workupdate"></span>
<span id="loaders2" style="display:none;">
<img alt="" src="dist/img/loader11.gif">
</span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$('#homeDB').on('click', function() {
$.ajax({
type:'POST',
url:'db.php',
// dataType: 'json',
data:{db:"homeDB"},
beforeSend: function(){
$("#loaders1").show();
},
complete: function(){
$("#loaders1").hide();
},
success:function(data) {
$("#homeupdate").html("Databasis Opgedateer");
},
error: function (error) {
$("#homeupdate").html(error);
}
});
});
$('#workdb').on('click', function() {
$.ajax({
type:'POST',
url:'db.php',
// dataType: 'json',
data:{db:"workdb"},
beforeSend: function(){
$("#loaders2").show();
},
complete: function(){
$("#loaders2").hide();
},
success:function(data) {
$("#workupdate").html("Databasis Opgedateer");
},
error: function (error) {
$("#workupdate").html(error);
}
});
});
</script>
<script>
jQuery(document).ready(function(){
// Basic Form
jQuery("#basicForm").validate({
highlight: function(element) {
jQuery(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(element) {
jQuery(element).closest('.form-group').removeClass('has-error');
}
});
// Error Message In One Container
jQuery("#basicForm2").validate({
errorLabelContainer: jQuery("#basicForm2 div.errorForm")
});
// With Checkboxes and Radio Buttons
jQuery('#genderError').attr('for','gender');
jQuery('#intError').attr('for','int[]');
jQuery("#basicForm3").validate({
highlight: function(element) {
jQuery(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(element) {
jQuery(element).closest('.form-group').removeClass('has-error');
}
});
jQuery("#basicForm4").validate({
highlight: function(element) {
jQuery(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(element) {
jQuery(element).closest('.form-group').removeClass('has-error');
},
ignore: null
});
// Validation with select boxes
jQuery("#flowers, #fruits").select2({
minimumResultsForSearch: -1
});
});
</script>
</body>
</html>
<?php include_once 'footer.php'?>
If you modify the button and assign it a type='button' attribute you should be able to observe (in the console) that each button now fires the ajax request and the form is no longer submitted as per the default behaviour.
$(document).ready(function() {
$('#homeDB').on('click', function() {
console.log(this)
$.ajax({
type: 'POST',
url: 'db.php',
// dataType: 'json',
data: {
db: "homeDB"
},
beforeSend: function() {
$("#loaders1").show();
},
complete: function() {
$("#loaders1").hide();
},
success: function(data) {
$("#homeupdate").html("Databasis Opgedateer");
},
error: function(error) {
$("#homeupdate").html(error);
}
});
});
$('#workdb').on('click', function() {
console.log(this)
$.ajax({
type: 'POST',
url: 'db.php',
// dataType: 'json',
data: {
db: "workdb"
},
beforeSend: function() {
$("#loaders2").show();
},
complete: function() {
$("#loaders2").hide();
},
success: function(data) {
$("#workupdate").html("Databasis Opgedateer");
},
error: function(error) {
$("#workupdate").html(error);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="basicForm" action="updateDatabase.php" method="post" name="basicForm">
<div class="wrapper">
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-25">
<div class="card">
<div class="card-header">
<h3 class="card-title">Update Database</h3>
</div>
<div class="card-body">
<p>
<button type='button' position="relative" class="btn btn-block btn-outline-danger btn-lg c1" id="homeDB">Home DB</button>
<span id="homeupdate"></span>
<span id="loaders1" style="display:none;">
<img alt="" src="dist/img/loader11.gif">
</span>
</p>
<p>
<button type='button' position="relative" class="btn btn-block btn-outline-success btn-lg c1" id="workdb">Work DB</button>
<span id="workupdate"></span>
<span id="loaders2" style="display:none;">
<img alt="" src="dist/img/loader11.gif">
</span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>

How to display a pop up notification laravel using ajax?

How to display a pop-up notification in admin side when a customer click an order?. Now its not getting the pop-up notification?.when inspect the values getting.
var audio = document.getElementById("myAudio");
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
}
Ajax
<script>
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
dataType: 'json',
success: function (response) {
let data = response.data;
if (data.new_order > 0) {
playAudio();
$('#popup-modal').appendTo("body").modal('show');
}
},
});
}, 1000);
Controller
public function order_data()
{
$new_order = DB::table('orders')->where(['checked' => 0])->count();
return response()->json([
'success' => 1,
'data' => ['new_order' => $new_order]
]);
}
pop up code
<div class="modal" id="popup-modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12">
<center>
<h2 style="color: rgba(96,96,96,0.68)">
<i class="tio-shopping-cart-outlined"></i> You have new order, Check Please.
</h2>
<hr>
</center>
</div>
</div>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function(){
setInterval(function () {
$.ajax({
url: '{{route('get-order-data')}}',
type: 'GET',
dataType: 'json',
success: function (response) {
$.each(response.new_order, function (key, value) {
if (value.new_order > 0) {
playAudio();
$('#popup-modal').modal('show');
}
});
}
});
}, 1000);
});
</script>
Controller
public function order_data()
{
$data = DB::table('orders')->where('checked', 0)->get();
$count = $data->count();
$res['new_order'] = array([
'success' => 1,
'new_order' => $count
]);
return response()->json($res);
}
You are displaying the popup through modal window. You can trigger the modal window through javascript. I hope the below code will be useful for you. Try this code in jsFiddle with jQuery enabled. Append the javascript code inside the ajax code where you need to display the notification.
$('.btn').click(function () {
$("#myModal").modal('show');
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="myModal" class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<button class="btn">
Submit
</button>

Is there a possibility to bind the Form to a modal bootstrap window without using the load call?

I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.

Modal button didn't fire its click event

I have this modal and in SaveChangesofCollectorID id
<div class="modal fade" id="mymodal" role="dialog" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<input id="ToDate" name="ToDate" readonly="readonly"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" style="width:40px;">no</button>
<button id="SaveChangesofCollectorID" data-dismiss="modal" type="button" class="btn btn-default" style="width:40px;">yes</button>
</div>
</div>
</div>
it didn't fire its event
, or just fire the first alert ,
even I remove the data-dismiss="modal"
and here is my experiment
$("#SaveChangesofCollectorID").click(function () {
alert("inserted here");
$.ajax({
type: "POST",
url: "UnloadingCalendar.aspx/SaveChangesofCollector",
data: JSON.stringify({ CollectorID: CollectorID, FromDate: startday, ToDate: EndDate, DaysCount: countdays }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
OpenConfirmationModal();
},
error: function (msg) {
alert(msg.d);
},
complete: function () {
}
});
});
</div>
Here is a working fiddle: https://jsfiddle.net/code4pi/6rvd073L/
There is nothing wrong with your code, you just need to wrap your js in a script tag if you are going to have it inline (or better yet, move the js into its own file):
<script>
$("#SaveChangesofCollectorID").click(function () {
alert("inserted here");
$.ajax({
type: "POST",
url: "UnloadingCalendar.aspx/SaveChangesofCollector",
data: JSON.stringify({ CollectorID: CollectorID, FromDate: startday, ToDate: EndDate, DaysCount: countdays }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
OpenConfirmationModal();
},
error: function (msg) {
alert(msg.d);
},
complete: function () {
}
});
});
</script>

Insert Data from Modal Bootstrap MVC 4 + JQuery (Post Method)

I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>

Categories