I'm using a BS Modal to show the feedback on a newsletter form.
It uses AJAX and PHP to insert the e-mails on DB and returns the STATUS.
The PHP and the AJAX response are working fine, with validations and everything, BUT, when I call the Modal using the JS to show the feedback, the modal doesn't close anymore, can't be dismissed.
The modal:
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">ENGINE|Sistemas</h4>
</div>
<div class="modal-body">
<p id="response"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
And the JS:
$(function()
{
var form = $('#newsletter-form');
$(form).submit(function(e)
{
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
// ----------------------------------------
// Success
// ----------------------------------------
.done(function(response)
{
$('#myModal').modal('show');
$('#myModal, #response').replaceWith(response);
$('#newsletter-email').val('');
})
// ----------------------------------------
// Error
// ----------------------------------------
.fail(function(data)
{
if (data.responseText !== '')
{
$('#myModal').modal('show');
$('#myModal, #response').replaceWith(data.responseText);
}
else
{
alert('Ocorreu um erro! Seu email não foi cadastrado.');
}
});
});
});
I don't understand why tho modal shows up perfectly with the response, but simply doesn't close anymore...
Any help?
do you see error js in console?? if no, try this :
$("#myModal").on('hidden', function(){
$("#myModal").remove();
$('.modal-backdrop').remove();
});
Well, now it's working.
I don't know why, but the response was blocking the modal to behave correctly.
Solved just changing:
$('#myModal').modal('show');
$('#myModal, #response').replaceWith(data.responseText);
to
$('#myModal').modal('show');
$('#response').text(data.responseText);
=)
Related
I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})
on click add area button my modal should be closed but it is not working. everything looks fine but i can not find error. id="category-popup" should close modal by $("#category-popup").modal('hide'); but it is not working can someone help me?
<div class="modal fade" id="category-popup" tabindex="-1" role="dialog" aria-labelledby="category-
popup" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Area</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="{{ route("save.area.ajax") }}" class="category-form">
{{ csrf_field() }}
<div class="form-group">
<label>Area Name</label>
<input type="text" name="name" class="form-control old-category" required="">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary btn-block add-area-submit-btn">Add
Area</button>
</div>
</form>
</div>
</div>
</div>
</div>
java script
$('.add-category').click(function(event){
event.preventDefault();
$('.old-category').val('')
$('.category-form').attr('action' , '{{ route("save.area.ajax") }}');
$('#category-popup .modal-title').html('Add Area');
$('#category-popup .modal-footer button').text('Add Area');
});
$(document).on('click', '.add-area-submit-btn', function(e){
e.preventDefault();
var btn = $(this);
if($('.category-form .old-category').val() != ""){
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res){
$("#area-select").html(res);
$("#category-popup").modal('hide');
}
});
}
});
The syntax for hiding modal is correct but please make sure that your $.ajax request is succeeding. Try doing console.log() in $.ajax success. Or add error in your ajax so you could know the error
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res) {
console.log("ajax request success");
$("#area-select").html(res);
$("#category-popup").modal('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ajax request failed: " + errorThrown);
}
});
check errors in the cnsole it submit area in option field but not closed
Hm, weird, are you sure you include jQuery correctly? Could you show your included scripts?
jQuery should be like: <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
In JavaScript one error results in broking whole script. And without jQuery your "modal" action will not work. I think it's the reason why your script not working.
I have table in modal with edit button to update the user details
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">User Info</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form>
<div class="modal-body edit-info" >
</div>
<div class="modal-footer">
<button type="submit" class="roomupdate btn btn-warning">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
and my ajax code is
$(document).on('click', '.roomupdate', function(){
ev.preventDefault();
$id= $('#id').val();
$building=$('#building').val();
$floorno=$('#floorno').val();
$roomno=$('#roomno').val();
$priority=$('#priority1').val();
$nobeds=$('#nobeds').val();
$('#editModal').modal('hide');
$.ajax({
type: "POST",
url: "addroomlist.php",
async: false,
data: {
building: $building,
id: $id,
floorno: $floorno,
roomno: $roomno,
priority: $priority,
nobeds: $nobeds,
roomupdate: 1,
},
success: function(){
showUser();
},
});
});
and my edit button code to call modal with user info.
<td> <button data-id='<?php echo $row['id'] ?>' class='roomedit btn btn-warning'>Edit</button></td>
when i first click save button after modify the details its working fine and modal closed with
$('#editModal').Modal('hide');
when i click edit button second time Modal not show up until i reload the page.
where it went wrong please help
In your ajax code remove $('#editModal').modal('hide'); from the line where you are using right now and put it in success function of ajax.
Like:
success: function(){
$('#editModal').modal('hide');
showUser();},
and if you are using location.reload(); in your showUser(); function then it will work but as far i know i think you did not add it in showUser(); so add also location.reload(); after showUser(); function or at the end of code written in showUser(); function.
And one more thing do you write any code by which clicking on edit button the modal should open in javascript?
I have Modal in view for making new record in Database.
View for it in Partial View
Here is code of view
<script src="~/Scripts/jquery-3.1.1.js"></script>
For AJAX I using this code
<script>
$(document).ready(function () {
$('#save_quest').click(function () {
savequestion();
});
});
function savequestion() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Question_new: $('#question').val(),
Answer: $('#answer').val(),
Preparing: $('#prepare').val(),
Retries: $('#retries').val(),
},
url: '#Url.Action("CreateNewQuestion", "Questions")',
success: function (da) {
if (da.Result === "Success") {
$('#myModal').modal('hide')
//window.location.href = da.RedirectUrl;
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I need to hide modal when AJAX call is Successful
I try this $('#myModal').modal('hide')
Here is my modal on Primary View
<div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#Html.Partial("~/Views/Questions/CreateQuestion.cshtml")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
How I can hide it on AJAX Success?
You can try any of the below option in your ajax success block. Hopefully it will solve your problem.
$("#myModal").modal('hide');
OR
$('#myModal').modal('toggle');
OR
$('#myModal').removeClass('show');
OR
$('#myModal').modal().hide();
OR
$("#myModal .close").click();
OR
$("#myModal .close").trigger("click");
I found solution
Just need to write
$('#myModal').hide();
This is not the proper way.
$('#myModal').hide();
The proper way
$("#myModal").modal('hide');
Have you try adding bootstrap.js in your page? if not please include it in your page and then test. It should work.
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()