I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};
Related
I am making an AJAX request to get an JSON array, upon success another AJAX request is performed and the contents are populated to the div of a bootstrap modal via jquery append function. Everything works correctly for the first selection, however, once I close the modal and attempt another entry the append function no longer populates the div. I attempted to empty the contents of the div and also tried the clone function but no matter what the contents are not repopulated until a page refresh. I tried logging to the console and the data is correct and repopulated with each click. Sorry if my code is terrible, still learning. Below is the code I am using. Any help would be appreciated.
function makeModal({first_name, last_name, id}) {
return `
<div class="modal fade" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">${first_name} ${last_name}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>${last_name}</p>
<p>${id}</p>
<p id="job_history"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>`;
}
//onclick event
$(document).on('click', '.applicant_detail', function(e) {
var id = $(this).data('id');
//$('#job_history').empty();
$('#myModal').modal('dispose');
$.ajax({
type: "POST",
url: "/admin/get_applicant",
dataType: 'json',
data: {id:id},
success: function(data) {
var count = Object.keys(data).length;
$.each(data, function(index, element) {
var m1 = $(makeModal({last_name:element.last_name, first_name:element.first_name, id:element.id}));
document.body.insertAdjacentHTML('beforeend', m1);
m1.modal('show');
});
$.ajax({
type: "POST",
url: "/admin/get_job_history",
dataType: 'json',
data: {application_id:id},
success: function(data) {
var count = Object.keys(data).length;
$.each(data, function(index, element) {
$('#job_history').append("Job Title: " + element.job_title + '<br>').clone();
console.log('Job Title: ' + element.job_title);
});
},
});
},
});
});
I figure it out. I needed to destroy the modal created via my makeModal function. So I removed the div with each click event. Not sure if this is the best way but it works.
$('#myModal').remove(); //added this below the click event
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.
I'm creating a service where I'm changing some data in DB via bootstrap modal dialog. After uploading file I'm showing name of this in my modal dialog body. But I can not see the name of the file what I've just uploaded, I have to close dialog and then open it again, without it I'm not able to see the actual name of uploaded file.
The question is: How to refresh "modal-body" of modal dialog without closing it?
Here is my modal html:
<div class="modal fade" id="editModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="width: 535px">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="dialog-edit"></div>
<div id="EditStatus"></div>
</div>
</div>
</div>
and my javascript:
tab.on("click", ".btnUpload", function (e) {
var formData = new FormData();
var id = $(this).closest("tr").find('#fileId').text();
var file = document.getElementById("FileUpload").files[0];
formData.append("id", id);
formData.append("file", file);
$.ajax({
type: "POST",
url: "/Events/UpdateJsionFile",
contentType: false,
processData: false,
dataType: "JSON",
data: formData,
success: function (data) {
if (!data.success) {
var res = $('<div style="color:red;">' + data.error + '</div>')
$('#uploadStatus').html(res);
}
else {
$('#uploadStatus').html("File #1 uploaded!");
}
}
});
});
Everything is working perfect but I have no idea how to refresh data after uploading?
Can somebody help me with it?
I've solved it like this:
first I've created a variable with file name:
var fileName = document.getElementById("FileUpload").files(0).name;
and then, after success in my ajax:
$('.FileUpload').html(fileName);
hope it will help somebody, who was looking for the same thing...
I want to show a dialog with jquery after another dialog is closed.
Here is the first dialog
When I press the Close button another dialog needs to be showed. This dialog which has a drop down, and I need to populate this dropdown with ajax call.
The problem is that I keep get this error on console: TypeError: $(...).get(...) is undefined. and the method from the controller is never reached.
This is the code that I'm using:
<script type="text/javascript">
$("#saveGeometryType_dialog").draggable({ handle: ".modal-header" });
function saveElements(options) {
}
function closeDialog(options) {
var $temp = $("<input/>", { id: 'temp' });
//$temp.val($(options.element).text()).select();
//document.execCommand("copy");
//var title = $("#geometry-dialog").dialog("option", "title");
//console.log($temp);
$temp.remove();
var title = "Linestring";
$('#saveGeometryType_dialog').modal('show');
$.ajax({
type: "POST",
url: "PlotDescriptions/GetCodes/" + title,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#ddlCode").get(0).options.length = 0;
$("#ddlCode").get(0).options[0] = new Option("Select code", "-1");
$.each(msg.d, function(index, item) {
$("#ddlCode").get(0).options[$("#ddlCode").get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function() {
$("#ddlCode").get(0).options.length = 0;
alert("Failed to load names");
}
});
}
</script>
<div class="modal fade" tabindex="-1" role="dialog" id="saveGeometryType_dialog">
<div class="modal-dialog" role="document">
<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">Save geometry</h4>
</div>
<div class="modal-body">
<p></p>
<div class="saveGeometryType-header">
<div class="row">
<div class="col-md-4"> Cod </div>
<div class="col-md-4"> <select id="ddlCod">
</select> </div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="saveElements({ 'element': '#saveGeometryType_dialog .modal-body > p', 'target': 'saveGeometryType_dialog .modal-body' });$('#saveGeometryType_dialog').modal('hide');" type="button" class="btn btn-primary">Save</button>
<button onclick="closeDialog({ 'element': '#saveGeometryType_dialog .modal-body > p', 'target': 'saveGeometryType_dialog .modal-body' });$('#saveGeometryType_dialog').modal('hide');" type="button" class="btn btn-default">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
This is the controller method that I need to reach. The parameter from the method should be the title from the first dialog, in this case the Linestring.:
[WebMethod]public static ArrayList GetCodes(string geometryType)
{
return new ArrayList()
{
new { Value = 1, Display = "Code1" },
new { Value = 2, Display = "Code2" }
};
}
Any help is appreciated.
I have a slight problem when pop-up is closing; modal-backdrop is not closing.
This code blog for opening pop-up:
<script>
$('div.ProjePartialGovde').click(function (el) {
var projeid = $(this).data('id');
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjeOzetPartial", "Home")',
data: { projeID: projeid,ilID:#ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
$("#detayModal").modal();
});
});
And this is my pop-up page:
I'm having trouble with my back button. When I clicked back button it goes backwards but there is something gray on the screen wich is: "modal-backdrop in"
<div class="modal" id="detayModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form>
<div class="form-group">
<label class="form-control">Başlangıç / Bitiş Tarihleri: #Model.SozBasTarihi / #Model.SozBitisTarihi</label>
</div>
<div class="form-group">
<label class="form-control">Nakdi ve Fiziki Tamamlanma Oranları: %#Model.NakdiTamOrani / %#Model.FizikiTamOrani</label>
</div>
</form>
</div>
<div class="modal-footer">
<!-- I HAVE PROBLEM HERE -->
<button class="ProjeListesiGeri" data-dissmiss="modal" data-backdrop="false">BACK</button>
</div>
</div>
</div>
</div>
<!-- GO BACK CODE -->
<script>
$('.ProjeListesiGeri').click(function (el) {
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjelerListesiPartial", "Home")',
data: { ilID: #ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
});
});
</script>
How can I solve this problem?
I solve the problem. I added in my back code this line: $("#detayModal").modal('hide'); and it is working.
So full code:
<script>
$('.ProjeListesiGeri').click(function (el) {
$("#detayModal").modal('hide'); <!-- I added this line. -->
$('.popupListe').html('içerik hazırlanıyor...');
$.ajax({
method: "get",
url: '#Url.Action("ProjelerListesiPartial", "Home")',
data: { ilID: #ViewBag.ilID }
})
.done(function (msg) {
$('.popupListe').html(msg);
});
});
</script>