How to reset modal contents? - javascript

The process is like this.
A user searches any words in a search form. Ajax calls with the word and gets the data, then it will be showed with the modal.
So, I tried to make modal dynamically with ajax.
But the modal contents didn't change once it called.
1) This is the function include a search form and it calls the modal.
function answer() {
//console.log('answer');
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = `<!-- file form start -->
<!-- file form end -->
<label class="col-md-2 col-form-label">문의내용</label>
<!-- text form start -->
{!! Form::open([ 'route' => ['qnamembercreate', $qnaMemberData->idx], 'method' => 'post', 'files' => true, 'accept-charset' => 'utf-8','class' => 'col-md-10 col-xs-9' ])!!}
<div class="col-sm-6 offset-md-6 p-0">
<div class="input-group">
<input type="text" id="f_search" name="f_search" class="form-control">
<span class="input-group-append">
<button type="button" class="btn waves-effect waves-light btn-inverse" onclick="faq_search()">Search</button>
</span>
</div>
</div>
<input type="hidden" name="subject" value="{{ $qnaMemberData->subject }}">
<textarea id="answer_content" class="mb-0" rows="20" style="width:100%;" name="add_answer"></textarea>
<div class="form-group">
<input name="fileToUpload" type="file" class="filestyle" data-input="false" id="filestyle-1" tabindex="-1" style="display: none;">
<div class="bootstrap-filestyle input-group">
<div style="position: absolute; width: 100%; height: 35.375px; z-index: -1;"></div>
<span class="group-span-filestyle " tabindex="0">
<label for="filestyle-1" style="margin-bottom: 0;" class="btn btn-secondary btn-sm fload-right">
<input type="file" name="fileToUpload" class="filestyle-1" data-placeholder="" data-buttontext="첨부파일" data-buttonname="btn-secondary">
</label>
</span>
</div>
</div>
<button type="button" class="btn btn-danger btn-sm float-right ml-1 mt-1" onclick="history.back()">취소</button>
<button type="submit" class="btn btn-success btn-sm float-right mt-1">등록</button>
{!! Form::close() !!}
<!-- text form end -->`;
document.getElementById('replyData').appendChild(div);
document.getElementById('answer').remove();
$('#answer_content').summernote({
// placeholder: {!! json_encode($qnaMemberData->content) !!},
tabsize: 2,
height: 200,
lang: 'ko-KR',
fontNames: ['Gulim', 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', ],
fontNamesIgnoreCheck: ['Gulim'],
});
}
2) This is the 'faq_search' function when the user clicks the 'search' button.
function faq_search() {
var word = $('#f_search')[0].value;
//console.log(word);
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}
3) This is the 'faq_popup' function which is called after getting the data.
function faq_popup(data) {
var _data = data;
console.log("here", _data);
const appendedDiv = $(`
<div class="modal fade show" tabindex="-1" id="faqModal" role="dialog" style="positon:center;">
<div class="modal-dialog modal-dialog-centered">
<!-- Modal content-->
<div class="modal-content">
<div class="table-responsive">
<table class="table mb-0">
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
`);
const tbody = appendedDiv.find('tbody')[0];
_data.forEach(({ content, subject }, i) => {
//console.log(i);
const tr = tbody.appendChild(document.createElement('tr'));
tr.innerHTML = `
<th scope="row">${i + 1}</th>
<td><a style="cursor:pointer">${subject}</a></td>
`;
tr.querySelector('a').addEventListener('click', () => getContent(content));
});
$('#modal_place').append(appendedDiv);
$('#faqModal').modal('show');
}
I tried to reset the modal with this code below. But the problem is, once the modal content is cleared, the new data is not called at all.
$(document).ready(function(){
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('tbody td').html("");
});
});
I really don't get it. Because I call the 'faq_popup' after the ajax got the data, the new data should be showed. But it doesn't work as I think.
What did I wrong here?
** I also tried to wipe out the whole modal-content. The modal contents doesn't show up at all.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('.modal-content').html("");
});

I found the solution. Thanks to #KaseyChang, gave me the hint.
The reason was I didn't destroy the modal correctly. The modal was added and added on itself. So I just did this.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).remove(); <--- here!
});

In the AJAX function you can just empty() the modal before the call is made, using beforeSend. This way it will happen sequentially:
function faq_search() {
var word = $('#f_search')[0].value;
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
beforeSend : function() {
$('.modal-content').empty();
},
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}

Related

Is there a way to reload page and after that inmediately open a modal?

I want to refresh the page after I press the ".parseo" button and then open the "#modal_parseo" modal window but with this code all it does it's open the modal first then refresh the page and closes everything again.
What I tried so far(to clear cache and see If I could fix the issue I had without having to reload the page but the code works fine only after I reload the page before I open the modal):
$('#modal_parseo').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');//this doesn't do anything at all
});
And this:
$("#modal_parseo").on("hidden.bs.modal", function(){
graph_editor.html.set('');//this clears content inside froala editor
$("#tabla_grafico").html("");//this clears datatable I build using the data pasted inside froala editor
});
This is the HTML
<div class="modal fade" id="modal_parseo" tabindex="-1" role="dialog" aria-labelledby="modalLabelparseo" aria-hidden="true">
<div class="modal-dialog modal-98" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabelparseo">Constructor de Gráfico </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body-parseo">
<div class="row mt-2">
<div class="col-md-6">
<div id="froala-grafico"></div>
<input type="hidden" name="editor_grafico" id="editor_grafico">
<input type="hidden" name="id_temporal" id="id_temporal">
</div>
<div class="col-md-6" id="container_parseo">
<table id="tabla_grafico" data-pagination="false" data-classes="table table-hover table-condensed" data-striped="false" style="width: 100%;"></table>
<br>
<div id="graph_selector" style="display:none; text-align: center;" >
<p><b>Tipo de Grafico: </b></p>
<div class="cc-selector">
<input id="axes" type="radio" name="sel_graph" class="radio_selector" value="axes" checked/>
<label class="drinkcard-cc axes"for="axes"></label>
<input id="activity" type="radio" name="sel_graph" class="radio_selector" value="activity" />
<label class="drinkcard-cc activity" for="activity"></label>
<input id="pie" type="radio" name="sel_graph" class="radio_selector" value="pie" />
<label class="drinkcard-cc pie" for="pie"></label>
</div>
</div> <!--DIV SELECTOR TIPO GRAFICO -->
</div> <!--DIV COL MD 6 -->
</div> <!--DIV ROW -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
<button type="button" class="btn btn-info" id="limpiar_froala">Limpiar</button>
<button type="button" class="btn btn-warning" id="vista_preliminar">Vista Preliminar</button>
<button type="button" class="btn btn-success" id="guardar_grafico">Guardar</button>
</div>
</div>
</div>
Here is the js
window.accionesFila = {
'click .parseo': function(e, value, row, index) {
window.location.reload();
$('#modal_parseo').modal('show');
//FUNCTION TO SAVE DATA
$('#guardar_grafico').click(function() {
//TABLE ID
var $table = $('#tabla_grafico');
//console.log(editor);
//$("#editor_grafico").val(graph_editor.html.get());
//GRAPH TYPE SELECTOR VALUE
var graph_selector = document.querySelector('input[name=sel_graph]:checked').value
function getRowSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row;
})
}
//SAVE SELECTED ROWS HERE
var selectedRows = getRowSelections();
agrupacion_array = [];
//ITERATE
$.each(selectedRows, function(index, value) {
id_grafico = value.col_grafico_id;
agrupacion_array.push(value.val_agrupacion);
});
$.ajax({
url: 'inc/datos-graficos-data',
dataType : "json",
type: 'POST',
data: {
q: 'guardar_grafico',
id: row.id_indicador,
graph_id: id_grafico,
agrupacion: agrupacion_array,
datos: editor
},
async: false,
beforeSend: function() {
//$("#ventasGrafico").html("<img src='images/loading.gif'>");
},
success: function(json) {
$('#modal_parseo').modal('hide');
//SWAL
Swal.fire(
'Exito!',
json,
'success'
)
},
cache: true
});
}); //INSERT GRAPH
}
}
Edit: I added this inside the 'click .parseo' function
'click .parseo': function(e, value, row, index) {
//$('#modal_parseo').modal('show');
var url = window.location.href;
if (url.indexOf('#modal') > -1){
window.location.href.split('#')[0]//I tried this to remove the hash now but it doesn't work
} else {
url += '#modal'
}
window.location.href = url;
window.location.reload();
And this outside, thanks to the 1st answer
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_parseo').modal('show');
}
});
Edit2: I managed to remove the hash after I close my modal with this
$('#modal_parseo').on('hide.bs.modal', function(e) {
history.replaceState(null, null, ' ');
});
When you call window.location.reload(), the page is reloaded just like when you press f5 or hit enter on your url bar. This means your current page state is lost, so the execution of your code is interrupted and starts over from the beginning on the freshly loaded page.
What you could do is add a hash to your url when the user clicks the button (for example https://www.my.page/#modal) and then check if this is present when you load the page:
//this executes when the page is ready
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_perso').modal('show');
}
});
Note that if somebody bookmarks the page including the hash, this will also be executed.
In your edit, you are trying to use window.location.href.split('#')[0] to remove the hash from the url. By itself, this doesn't do anything - it is just a value. You need to assign the value to something. You can not assign the value directly to window.location.href here because this will make most browsers reload the page.
What you can do is use HTML5 history API like this for example:
window.history.pushState(null, document.title, window.location.href.split("#")[0]);

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

How get clicked id when clicked element in modal window?

I am beginner web developer.
I have code to dynamic load data to iframe:
$(document).ready(function () {
function loadMaterials(type, query) {
$.ajax({
type: 'GET',
url: '/getMaterials',
dataType: "text",
data: {
query: query,
type: type,
},
success: function (data) {
$('.dynamic-materials').html(data);
}
});
}
$('.product-material-front').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(2, "");
$('.select-material-title').html('MateriaĹ frontu')
$('.material-type-input').val(2);
$('#material-dialog-modal').modal('show');
});
$('.product-material-body').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(1, "");
$('.select-material-title').html('MateriaĹ korpusu');
$('.material-type-input').val(1);
$('#material-dialog-modal').modal('show');
});
});
<div id="material-dialog-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body pt-0">
<h3 class="select-material-title px-3"></h3>
<form method="get" action="{{ route('frontend.get.materials') }}" class="px-3 select-material-url">
<input type="hidden" name="type" value="" class="material-type-input">
<div class="inner-addon rounded-0 modal-search-form">
<i class="fa fa-search"></i>
<input type="text" class="form-control product-query-string-body"
placeholder="Szukaj produktu"
aria-label="Wpisz nazwę lub kod koloru"/>
</div>
</form>
<div class="row material-list px-5 pt-4 dynamic-materials">
</div>
</div>
</div>
</div>
</div>
It's work fine.
I need to change the classes of the clicked elements.
Additionally, I want to select select with the option selected.
I made a code like this:
$('.select-material-body').on('click', function(e){ console.log('ok');
if($('.material-type-input').val() == 1){
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-body]').val($(this).attr('id'));
$('.product-material-body').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
} else{
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-front]').val($(this).attr('id'));
$('.product-material-front').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
}
});
But unfortunately it doesn't work :(
How can i repair it?
My preview: http://serwer1356363.home.pl/_nauka/ - popup is visible after click select (with icon)
Please help me..
Since the modal content isn't append on the document, you can't bind event to it.
Instead, you can add an on() event to the body, passing your sub-selector :
$('body').on('click', '.select-material-body', function(e) { console.log('ok'); });

How to get the id from the database upon clicking the button via ajax

Here is the scenario, I am doing a message thread inside a modal. I want to show a message thread for a specific person using its reference number. My problem is I cannot pass the reference number to my controller and return to my blade (in message thread). Here are my Codes.
My modal for message thread
<div id="threadmessage" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Message Thread</h3>
</div>
<div class="modal-body" style="height: 300px;" >
<div class="row" style=" margin-left: 30px; margin-bottom: 5px; left: 20px; width: 550px; height: 200px; overflow: auto;">
<div>
#foreach ($messageThread as $thread)
{!!$thread->message!!}
<br>
#endforeach
</div>
<br>
</div>
<div>
<br>
<div class="col-md-2">
<b> Message: </b><br>
</div>
<div class="col-md-10">
<textarea required=" " id="messageContent" style="resize: none;" class="form-control" rows="2"></textarea>
</div>
</div>
<br>
</div>
<div class="modal-footer">
<div>
<button type="button" id="btn-message" class="btn btn-default" data-dismiss="modal" style="background-color: #3c5fa6; color: white;">
Send <i class="fa fa-paper-plane-o ml-1"> </i>
</button>
</div>
</div>
</div>
</div>
</div>
My Javasript for showing the message modal
$('#inquire_t tbody').on('click','#showMsg-btn',function(){
var flag = 6; // Approved
var refNumber = $(this).attr('value');
var cur_flag = $(this).attr('name');
var user = $("#username").html();
console.log(refNumber);
console.log(user);
$('#threadmessage').modal({"backdrop":"static"});
getMessage(refNumber, user);
});//btn-message
function getMessage(num, name){
var refNumber = num;
var username = name;
$.ajax({
url:'getAllMessage',
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: refNumber+'refNumber'+username+'&username',
// dataType:'TEXT',
success: function(data){
}
})
}
Button for Modal
"
Controller for getting the messages
public function getAllMessage(Request $request){
$refNumber = $request->get('refNumber');
$number = $refNumber;
$messageThread = DB::table('i_di_thread')->select('message')->where('refNumber', '=', $number)->get();
return view ('message', ['messageThread'=>$messageThread]);
}
My Route
Route::get('showInquiries','HomeController#getAllMessage');
Route::get('getAllMessage','HomeController#getAllMessage');
You can pass it by two methods and your data is not concatenated properly so :
Method 1 :
$.ajax({
...
data : { 'refNumber' : refNumber, 'username' : username },
...
});
Method 2 :
data:'refNumber='+ refNumber + '&username='+ username

JCrop and Ajax Image upload and crop (laravel 5, Jquery)

I am currently building and image upload and crop feature on a website. the work flow is as follows
1.upload button is pressed.
2.A modal opens with an upload box
code for 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">Upload Profile Picture</h4>
</div>
<div class="modal-body">
<div id="load" class="display-none" style="width:32px;margin:150px auto;"><img src="img/loading2.gif"></div>
<div class="upload-container">
{!! Form::open(['file' => true, 'Method' => 'POST', 'id' => 'profile-image-upload']) !!}
<div class="alert alert-danger display-none error">
<p>File must be an image</p>
</div>
<div class="form-group">
{!! Form::label('upload', 'Upload Photo') !!}
{!! Form::file('upload', ['id' => 'file-select', 'class' => 'form-control upload-box']) !!}
</div>
{!! Form::close() !!}
</div>
<div id="image-box" class="image display-none" style="text-align:center;">
<img id="large-image" src="" style="max-width:100%;max-height:500px;display:inline-block;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close-button" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
click the browse button and select a photo, this instantly triggers an ajax request to upload the image and return the path to it.
server side code:
Route::post('upload-profile-pic', function(){
$input['file'] = Request::file('upload');
$rules = ['file' => 'mimes:jpg,png,gif,jpeg'];
$validator = Validator::make(
$input,
$rules
);
if ($validator->fails())
return 'false';
$identifier = str_random(20);
$image = Image::make(Request::file('upload'));
$image->encode('png')->save(public_path(). '/profile-images/temp/' . $identifier . '.png');
return $identifier;
});
On ajax success I load the resulting image into a div and show this in the modal.
Javascript (Jquery):
$('input[type=file]').change(function () {
$('#load').show();
var formData = new FormData($('#profile-image-upload')[0])
$('.upload-container').hide();
$.ajax({
type: 'POST',
url: 'upload-profile-pic',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('#load').hide();
console.log("success");
if (data != 'false')
console.log(data)
$("#large-image").attr('src', '/profile-images/temp/' + data + '.png');
$('.image').show();
if (data == 'false')
$('.upload-container').show();
$('.error').show();
},
error: function (data) {
$('#load').hide();
console.log("error");
console.log(data);
}
});
});
$('#myModal').on('hidden.bs.modal', function () {
$('.error').hide();
$('.upload-container').show();
$('.image').hide();
$('#profile-image-upload').trigger("reset");
})
$('.close-button').on('click', function () {
$('.error').hide();
$('.upload-container').show();
$('.image').hide();
$('#profile-image-upload').trigger("reset");
});
I also have two functions that reset the modal if it is canceled, this just hides the image and shows the upload box.
This all works as it should but my problem is that i want to apply Jcrop to the image that is generated. I have tried many things
in the ajax success funtion i added this
$("#large-image").attr('src', '/profile-images/temp/' + data + '.png').Jcrop();
The above works the first time but if the modal is closed and then the user tries again it doesn't replace the old image with the new one.
I tried adding
.done(fucntion(){
$("#large-image").Jcrop(
});
This is the same as the last option, works the first time but doesn't work after that.
I have tried
var image = $("#large-image");
then adding this to my ajax success
image.Jcrop()
and adding this to the closing functions
image.destroy()
This is the same as the last time where it wors the first time and detroy() throws an error in the console.
JavaScript isn't my strong point and i'm quite stuck on this now, can anyone help?
Resolved this using the code below:
$("#large-image").attr('src', '/profile-images/temp/' + data['identifier'] + '.png').Jcrop({}, function () {
jcrop_api = this;
$('.modal-dialog').animate({width: ($('#large-image').width() + 50)});
});
then when closing the modal i call
jcrop_api.destroy()

Categories

Resources