Modal Not Show Before ajax - javascript

I have an Javascript on click event that will loop all of the json to store it to database with ajax and before that i already add some modal to popup before the loop is running. but the problem is the modal doesn't pop up before the loop is running and pop up after the loop is running this is my code
this i my javascript
$.fn.dataTable.ext.buttons.Mapping = {
text: 'Save To Database',
action: function (e, dt, node, config) {
$('#modal-respondent-upload').modal('show');
var filename = $("#xlf").val().replace("C:\\fakepath\\", "");
var obj = jQuery.parseJSON(output);
$.each(obj.hasil, function (key, value) {
var dataRespondent = {
json: JSON.stringify(value),
importSessionDataID: 1
}
console.log(dataRespondent);
var respondentID = simpleAjaxRequest(dataRespondent, "/UploadExcel/CreateRespondent/", "Import Respondent Data");
});
}
};
function simpleAjaxRequest(data, url, text) {
var id = 0;
$.ajax({
type: 'POST',
url: url,
data: data,
async: false,
success: function (data) {
//moveProgressBar(10, text);
id = data;
}
});
return id;
}
and my modal is like this
<div class="modal fade" role="dialog" id="modal-respondent-upload">
<div class="modal-dialog">
<div class="modal-content">
<h1><span id="kondisi-data-modal">0</span>/<span id="jumlah-data-modal">0</span></h1>
</div>
</div>
</div>

Related

How to get a value from controller and use this in javascript using MVC?

In my project , I get the error and success notifications as TempData from controller and in view , if they're not null I show user a notification seperately. Ever since I start to use FilePond , my TempData values became invisible. Hence, I try to add if-else conditions to javascript so I can show the notifications again. But the problem is , I can't get the TempData value to use in javascript. I researched and tried all recommendations but it still returns null. Any Idea how can I fix this ? I'm so close to end this but the only problem is TempData now.
My Controller (I made it shorter but in debug , I can get the tempdata value so nothing is wrong in here)
[HttpPost]
public async Task<IActionResult> Create(SaveCommand command)
{
TempData["error"] = _localizationService.GetLocalizedHtmlString("error");
return View();
}
View / Javascript Part (var test returns null)
<script type="text/javascript">
var myJsVariable = null;
var test = #Json.Serialize(#TempData["error"]);
$(document).ready(function (e) {
pond = FilePond.create(
document.querySelector('#ImageUrl'), {
allowMultiple: true,
instantUpload: false,
allowProcess: true
});
var frm = $('#form2');
if (myJsVariable != null) {
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal3").modal('show');
})
}
else if(myJsVariable ==null){
console.log("fail")
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal2").modal('show');
})
}
});
</script>
}
ps : This was a problem for a while so I created a random myJsVariable to understand where the problem is. But instead of using this , I need to use my tempdata values. (I cant even show my tempdata values inside my modals.)
This was a problem for a while so I created a random myJsVariable to
understand where the problem is. But instead of using this , I need to
use my tempdata values. (I cant even show my tempdata values inside my
modals.)
Well, the way are you trying to Retrieve value from temp data is incorrect. Here '' is very important. You could use below pattern to extract your #TempData["error"] then bind to javascript easily.
var tempData = ('#TempData["error"]');
Working Example For You:
Controller:
public IActionResult TempDataView()
{
TempData["error"] = "Temp Data From Controller";
return View();
}
Modal:
<div class="modal" tabindex="-1" role="dialog" id="formModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header" id="formModal">
<h5 class="modal-title"></h5>
</div>
<div class="modal-body"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<a onclick="BindTempDataToJavascript('#Url.Action("TempDataView","Todo",null,Context.Request.Scheme)','Bind Temp Data To Javascript')" class="btn btn-success text-white"><i class="fas fa-random"></i> Bind Temp Data To Javascript</a>
Script:
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script>
<script type="text/javascript">
BindTempDataToJavascript = (url, title) => {
//Retriving Temp Data and Binding to Javascript variable
var tempData = ('#TempData["error"]');
alert(tempData);
console.log(tempData);
$("#formModal").find(".modal-body").html(tempData);
$("#formModal").find(".modal-title").html(tempData);
$("#formModal").modal('show');
};
</script>
Output:

Display external link in modal panel

I have searched for this issue and although some of the solutions work none of them fit my issue.
I am creating links dynamically using ajax calls. When any of the links (styled as button) is clicked I need to show http:\\<IP-address> in the modal.
When links are created and I use "inspect" and copy what is rendered and paste it on top of the page and click it, it does show the content in modal pop up, so I know the script that displays content in modal works. But when I click on actual, dynamically created, links it opens the pop up with no content.
Here is a watered down version of what I have and what I have tried:
Modal popup:
<div class="modal fade" id="printerInfoModal" role="dialog" aria-labelledby="mainModalLabel" aria-hidden="true">
<div class="modal-dialog fade in">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" ClientIDMode="Static" Text=""></asp:Label></h4>
</div>
<div class="modal-body">
<iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>
</div>
<div class="modal-footer">
<button id="btnCloseModal" class="btn btn-info" data-dismiss="modal" aria-hidden="true" aria-label="Close">Close</button>
</div>
</div>
</div>
</div>
// Get a list of printers and for each get its status, printer property includes IP address
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterMapping",
cache: false,
data: "",
success: function (response) {
if (response !== "") {
try {
jResponse = JSON.parse(response.d);
$.each(jResponse, function (index, value) {
var printer = value;
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterStatus",
cache: false,
data: JSON.stringify({ PrinterHostnameIPAddress: printer.IPAddress }),
success: function (result) {
if (result !== "") {
var printerIP = 'http://' + printer.IPAddress;
//var redir = 'openInfo("' + printerIP + '")';
if (status == "Ready") {
$('<div/>', { class: 'col-sm-2' })
.append($('<a/>', { id: 'printer' + printer.IDN, class: 'form-control btn btn-success btn-block extLink', style: 'margin-bottom:5px', href:printerIP, text: status.replace(/\"/g, '') }))
.appendTo($('#printerStatusTable'));
// Not sure if below two lines work!
//It seems I cnnot add data-target: 'xxx' in attributes list part of "append"
$('#printer' + printer.IDN).attr('data-target', '#printerInfoModal');
$('#printer' + printer.IDN).attr('data-toggle', 'modal');
},
error: function (result) {
},
failure: function (result) {
}
});
})
$('#printerStatusTable').find('a').attr('data-target', '#printerInfoModal');
$('#printerStatusTable').find('a').attr('data-toggle', 'modal');
// Another think I tried
$('#printerStatusTable').find('a').attr('onclick', 'blah(' + $(this).attr('href') + ');');
JS:
// this function is hit if I copy/paste the html of the the link/button and click it; otherwise it is not called
$('.extLink').click(function (e) {debugger
e.preventDefault();
var frametarget = $(this).attr('href');
//clearIframe();
targetmodal = '#printerInfoModal';
$('#modeliframe').attr("src", frametarget );
});
function blah(){debugger
var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function blah(frametarget){debugger
//var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function clearIframe() {
var iframe = $('#modeliframe');
var html = "";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
}
This works, when I add the link manually; what I actually see when I click on the ajax-created link/button and select "inspect":
<a class="form-control btn btn-block extLink btn-success" id="printer10" style="margin-bottom: 5px;" href="http://1.2.3.4" data-toggle="modal" data-target="#printerInfoModal">Ready</a>
Can anyone see what am doing wrong or what I am missing?
So, if you are adding the button dynamically after the page loads, you'll need to target the document with your click handler like this:
$(document).on('click', '.extLink', function() {
// Do what you want when the button is clicked.
});
This is because when your page loads all of your Jquery handlers are attached to the DOM. If the element doesn't exist, then you are attaching them to nothing basically.

Editing Fullcalendar javascript

I'm editing fullcalendar to adapt it to my needs.
First of all here is the code:
<!----HTML---->
<link href='assets/css/fullcalendar.css' rel='stylesheet' />
<link href='assets/css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='assets/js/moment.min.js'></script>
<script src='assets/js/jquery-ui.min.js'></script>
<script src='assets/js/fullcalendar_not_min.js'></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">Scegli Zona di Servizio</h4>
</div>
<div class="modal-body" id="myModalBody">
<div class="form-group">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="mySelect">
<?php
foreach($zone_servizio_array as $zona){
echo '<option value="'.$zona->getId().'">'.$zona->getNome().'</option>';
}
?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save();" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
<body>
<div id='wrap'>
<div id='external-events'>
<h4>Agenti</h4>
<?php
foreach ($agenti_array as $agente){
echo '<div class=\'fc-event\'>'.$agente->getNome().' '.$agente->getCognome().'</div>';
}
?>
<p>
<img src="assets/img/trashcan.png" id="trash" alt="">
</p>
</div>
<div id='calendar_buttons' align="left">
<div class="btn-group" role="group" aria-label="..." >
<button type="button" class="btn btn-success"><span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span> Salva</button>
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Ripristina</button>
</div>
</div>
<div id='calendar'></div>
<div style='clear:both'></div>
<xspan class="tt">x</xspan>
</div>
</body>
Here is the Javascript:
<script>
var salva = 0; //control variable
function save(){//to change the control variable value
salva = 1;
}
function saveEvent(event, title, start, zone){
$('#myModal').modal('show');
$('#myModal').on('hidden.bs.modal', function (e) {
zona_servizio = document.getElementById('mySelect').value;
if(salva == 1){
console.log('before save event', event, title, start, zone);
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&zona_servizio='+zona_servizio,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
}else{
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
});
//$('#calendar').fullCalendar('updateEvent',event);
salva = 0;
console.log('end save event', event);
}
$(document).ready(function() {
zone = "01:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .fc-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
**eventReceive**: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
console.log('event Receive', event, title, start, zone);
saveEvent(event, title, start, zone);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
process.php
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once __ROOT__.'/main/metodi.php';
include('config.php');
sec_session_start();
$type = $_POST['type'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$zona_servizio = $_POST['zona_servizio'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `zona_servizio`) VALUES('$title','$startdate','$startdate','false','$zona_servizio')");
$lastid = mysqli_insert_id($con);
$_SESSION['array_last_events'][] = $lastid;
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT calendar.id, calendar.title, calendar.startdate, calendar.enddate, zona_servizio.nome as zona_servizio, calendar.allDay FROM calendar LEFT JOIN zona_servizio on calendar.zona_servizio = zona_servizio.id");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$e['zona_servizio'] = $fetch['zona_servizio'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
}
if($type == 'zone_servizio')
{
$zone = array();
$query = mysqli_query($con, "SELECT * FROM zona_servizio");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['nome'] = $fetch['nome'];
$e['id_comune'] = $fetch['id_comune'];
array_push($zone, $e);
}
echo json_encode($zone);
}
?>
Explanation of the code and issue:
I'm using fullcalendar to drag and drop some events on the calendar. In the javascript this corresponds to Event receive.
After the event drop, the function saveEvent is called.
A modal is showed, with a select form.
Clicking on Save changes button, I get the selected option value and than I store the events information and this value in the DB using Ajax.
It's very linear.
When I drop the first event, everything works fine. The problem is when I drop more than one event without manually refresh the page.
Here what happen: I store the second event, but I re-store the first event too.
If I drop a third event, I re-store the first two events and the third.
I need help to understand the reason.
In the javascript I insert some console.log.
Here's the console output:
console_output
You can see at the end that the console.log "before save event" is repeated two times, with the first and second events data.
This means that at the second Event drop, the saveEvent function is called twice. So why does this happen?
I hope my question was clear. Thanks to everyone!
I resolved the issue. It was linked to the bootstrap modal.
I found this other post that helped me: link

Delete data after save inside modal bootstrap 3

I have 2 pb to resolve with my form inside modal bootstrap 3
First : My data is saved twice
Second : When I save a data how to delete the data in input and textarea inside myform or if I reload the modal
Thanks
first : catagories.php ==> call a modal
<style>
.modal-dialog {
width: 900px!important;
}
</style>
<a data-toggle="modal" href="<?php echo FILENAME_MANUFACTURERS_POPUP;?>" data-target="#myModal"><?php echo osc_image (DIR_WS_ICONS . 'create.gif', TEXT_CREATE) ?></a>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body"><div class="te"></div></div>
</div> <!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
**second : inside my modal :manufacturers_popup.php**
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<form name="ajaxform" id="ajaxform" action="manufacturers_popup_ajax.php" method="post">
<input> .......</input>
<textarea>........</textarea>
</form>
<script type="text/javascript" src="ext/javascript/bootstrap/js/bootstrap_ajax_form.js" /></script>
third : my ajax files : bootstrap_ajax_form.php
$(document).ready(function() {
$("#simple-post").click(function() {
$("#ajaxform").submit(function(e) {
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
Several things wrong here.
A submit handler will bind to the submit event of the form, you don't need to do it inside a click handler for the submit button.
You don't want to trigger the submit the way you are doing , that is what is causing the second save. WHen you click on a submit button inside a form, it will automatically trigger the form submit.
Try it this way:
$(function () {
$("#ajaxform").submit(function (e) {
e.preventDefault(); //STOP default action do this first in case any errors thrown in code
var form = this;
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">' + data + '</code></pre>');
/* cleanup now */
form.reset()
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
});
});
To clear your form Data you can use the below function
function clearFormFields(div){
$('#'+div).find('input:text, input:hidden, input:password, input:file, select, textarea').val('');
$('#'+div).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
Add this function to your JS, and in your case you can call clearFormFields("ajaxform") when ever you want to clear the form fields
In case, If you need to clear your form data on every time hiding the Modal, you can bind it on your Bootstrap modal as
$('#myModal').on('hidden', function () {
clearFormFields("ajaxform");
})
see the other events on a Bootstrap modal here
In case the above function didn't clear your CKeditor text field, you can use the CKEditor API method setData see the detailed documentation here
Good Day
Ok, thanks for all orientation.
I found the solution
$(function () {
$("#ajaxform").submit(function (e) {
e.preventDefault(); //STOP default action do this first in case any errors thrown in code
var form = this;
$("#simple-msg").html("<img src='images/icons/loadingAnimation.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code class="prettyprint">' + data + '</code></pre>');
/* clear ckeditor instance */
for(k in CKEDITOR.instances){
var instance = CKEDITOR.instances[k];
instance.setData( '' );
}
// cleanup now
form.reset()
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
});
});

Grails render gsp page after popup window

I have a popup window using twitter bootstrap, then I have a javascript that call a controller action. On that controller action I render a string to be displayed in the popup window. And on that action I have another render, It render the gsp page itself because a value is added in a textarea. How to make the second render work?
GSP:
<g:javascript>
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
}
}).success(function(data) {
$('.modal-body').html(data);
$('#myModal').modal('show');
});
}
</g:javascript>
<g:textField name="inputField" />
<!-- Button to trigger modal -->
+
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Members</h3>
</div>
<div class="modal-body">
</div>
</div>
<textArea name="listField" id="listField" rows="50" cols="6" readonly>${params.Result}</textarea></td>
Controller:
def addEG_Create = {
def LdapName
def result
def membersString = ''
def members = ''
result = proxy.getWLSGroupParticipants(params.inputField)
if(result != null){
params.egId = params.id
LdapName = proxy.getWLSGroupsForUser(result[0])
int index
if (LdapName.size()>1){
index = 0
//find the index number for the correct Ldap name
for (int i = 0; i < LdapName.size(); i++) {
if (LdapName[i].toUpperCase() == params.inputField.toUpperCase()){
index = i
}
}
}else{
index = 0
}
if(params.listField.find(LdapName[index])){
params.Result = params.listField.trim()
membersString = params.listField.replace('\n',',')
flash.message = params.inputField + " exist in the list!"
}else{
flash.message = ""
if(params.listField!=''){
if(params.listField.charAt(params.listField.length()-1)=='\n'){
params.listField = params.listField.substring(0,params.listField.length()-1)
}
params.Result = params.listField.trim() + '\n' + LdapName[index].trim()
membersString = params.Result.replace('\n',',')
//membersString = params.listField.replace('\n',',') + LdapName[index]
} else{
params.Result = LdapName[index].trim()
membersString = LdapName[index]
}
}
for (int i = 0; i < result.size(); i++) {
if(i == 0){
members = result[i].trim()
}
else {
members = members + '\n' +result[i].trim()
}
}
params.Members = members
} else {
flash.message = params.inputField + " not found in LDAP. Please contact TECH CUST CARE"
params.Result = params.listField.trim()
membersString= params.listField.replace('\n',',')
//println "Not Found"
}
membersString = membersString.replace('\r','')
MGExecutingGroupInstance.members = membersString.trim()
render(members)
render(view:'create')
}
Jeka, you can't render two thinks like this
render(members)
render(view:'create')
the better way i see you can do this is something like this:
In your controller you can render your data as JSON:
def addEG_Create () {
...
...
render([members:members, openWin:'create'] as JSON)
}
And in your .gsp you should do shomething like this:
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
},
dataType: 'json',
success(function(data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
$('#myModal').modal('show');
});
}
I don't have tested this code, maybe it can have some errors, but the logic is this.
Updated
function callEgCreate() {
$.ajax({
type: "GET",
url: "testeChamada",
data: {"inputField": $("[name='inputField']").val(), "listField" : $("[name='listField']").val()},
dataType: 'json',
success: function (data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
console.log(data['members']);
}
});
}
Ps1: In your controller when you say render render([members:members, openWin:'create'] as JSON) you have to receive the data in your page with the key of map [key:value]
Ps2: In your data: you have made a mistake. It should be a map with Key:Value

Categories

Resources