How to show modal after Ajax success? - javascript

After the article is successfully added, the modal showing the message should appear, but I'm just getting errors. So far this is my code:
Modal:
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<h4 class="modal-title">Awesome!</h4>
</div>
<div class="modal-body">
<p class="text-center">Your booking has been confirmed. Check your email for detials.</p>
</div>
<div class="modal-footer">
<button class="btn btn-success btn-block" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
Ajax:
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
var f = CKEDITOR.instances.text.getData();
var text = String(f);
var n=text.length;
var title = $('#title').val();
var docu_id = $('#docu_id').val();
var hidden_snippet = $('#hidden_snippet').val();
if (n!=0) {
$.ajax({
type: 'POST',
url: '/knowmore/index.php/ask_controller/book_add',
data: {text:text,title: title,hidden_snippet: hidden_snippet,docu_id:docu_id},
success: function (data)
{
$("#myModal").modal('show')
location.replace('/knowmore/index.php/index_controller/documentation/'+docu_id+'');
}
});
} else { alert('Enter contents of the Article!'); }
});
</script>
I used $("#myModal").modal('show') to show it but all I'm getting is an error saying modal is not a function.

If you all you need is to open a bootstrap modal, then just use
$('#myModal').modal();

It's because jQuery doesn't know any function named modal by default. If you want to show the modal you can just use show() function.
Change following
success: function (data) {
$("#myModal").modal('show')
location.replace('/knowmore/index.php/index_controller/documentation/' + docu_id + '');
}
into
success: function (data) {
$("#myModal").show();
location.replace('/knowmore/index.php/index_controller/documentation/' + docu_id + '');
}

Write down the following code.
success: function(msg)
{
$("#myModel").modal("show");
}

Related

AJAX call not triggered on show.bs.modal

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....
})

Javascript methods stop working after writing another method in the same script tag

I have written a code on codeigniter framework for approve and disapprove leave of employees. The approval and disapproval worked fine before. But after I write another methods in the same script tag for showing the leave details of the employees the approval and disapproval stopped working.
What can I change in order to make the two buttons work. The two buttons are also inside the modal.
javascript
<script>
$(function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
$('#pedingLeaveRequest').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var current_leave_id = button.data('id');
var modal = $(this);
modal.find('input[name="current_leave_id"]').val(current_leave_id);
});
//approve button
$('#approvebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/approveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been approved!');
}
});
});
//disapprove button
$('#declinebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/disapproveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been disapproved!');
}
});
});
});
//show leave details on modal
$("#showleave").on('click','button',function(event){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
</script>
view:
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != "1")
{
echo '
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1">'.$row->user_name.'</h5>
<p class="mb-0 mt-0">'.$row->leave_start.' to '.$row->leave_end.'</p>
<p class="mt-0">'.$row->leave_type.'</p>
<button type="button" class="detailButton" href="<?php echo $id; ?>" data-id="'.$row->id.'" data-name="'.$row->user_name.'" data-toggle="modal" value="'.$row->id.'">View Request</button>
</div>
</li>
</ul>
';
}
}
?>
</div>
modal
<!-- Modal -->
<div class="modal fade" id="pendingLeaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Leave Request</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="leave_details" >
<p> </p>
</div>
<div class="modal-footer">
<input type="hidden" name="current_leave_id" id="current_leave_id" value="" />
<button type="button" id="declinebtn" class="btn btn-secondary" data-dismiss="modal">Decline</button>
<button type="button" id="approvebtn" class="btn btn-primary">Approve</button>
</div>
</div>
</div>
</div>
As you are replacing the $('#pendingLeaveRequest #leave_details').html(data); with new data so the button don't work.. Try to replace it with new id....
//show leave details on modal
//$("#showleave").on('click',function(){
$('.detailButton').on('click', function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details p').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
let me know if it is working..

Close modal on AJAX Sucess(ASP.NET MVC)

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 want to delete the image from my view page and table using jquery

here is my view page...
here my image is not getting deleted.the image name is not alerting when i give alert and not getting deleted..
<div class="modal fade" id="confirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
Are you sure you want to delete this image?
</div>
<div class="modal-footer">
<input type="hidden" name="image" id="img">
<button type="button" class="btn btn-default" data-dismiss="modal" id="modal-close">Close</button>
<button type="button" class="btn btn-danger" id="delete-ok">Ok</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function (){
$('#modal-close').click();
$("#file").change(function() { $('#upload-image').submit(); });
$('#upload-image').on('submit',(function(e){
e.preventDefault();
//alert()
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(result)
{
//$('#uploaded-img').html(result);
//location.reload();
}
});
}));
$(".fa-close").click(function(){
var image=$(this).attr('image');
alert(image);
$("#img").val(image);
});
$("#delete-ok").click(function(){
var image=$("#img").val();
alert(image);
var url='<?php echo base_url(); ?>admin_control/delete_upload_image';
alert(url);
var id=$("#product_id").val();
alert(id);
$.post(url, {image:image,id:id}, function(result)
{
//$('#uploaded-img').html(result);
location.reload();
});
});
});
my controler page is this...
public function delete_upload_image()
{
if($_POST)
{
$data=$this->session->userdata('image');
$f=$this->input->post('image');
$this->edit_image_delete($f);
unset($data[array_search($f,$data)]);
$this->session->set_userdata('image',$data);
var_dump('$data');
/*for editing */
if($this->input->post('id'))
{
$image=array_values($this->session->userdata('image'));
$data=array('image'=>json_encode($image));
if($this->input->post('table')=='gallery')
{
/*update gallery table*/
$this->roxmodel->update_gallery($this->input->post('id'),$data);
}
else
{
/*update product table*/
//$this->adminmodel->update_product($this->input->post('id'),$data);
}
}
$this->load->view('admin_control/ajax_show_upload_image',$data);
}
}
public function edit_image_delete($image)
{
if(file_exists('images/'.$image))
{
#unlink("./images/".$image);
}
if(file_exists('images/thumb/'.$image))
{
#unlink("./images/thumb/".$image);
}
return true;
}
here my image is not getting deleted.the image name is not alerting when i give alert and not getting deleted..

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