Opening modal in using ajax is not working - javascript

I have here the sample project that will get the value of the id of an attribute using ajax and then should show the modal using ajax.
The program that I've got is functioning well in terms of getting the id but my problem is the modal is not showing.
What I tested to know the problem is that I deleted the class="modal hide" in the modal and so the modal appeared below of the table and not in front of the whole page.
It just looked like another division under the table.
So now my problem is that the modal doesn't pop up. When the is clicked nothing happens if there is an attribute class="modal hide" of the modal, but if there is no attribute like that it is working there is a modal but it is not a pop up.
It is like another division under the table.
What's wrong with my code?
<a type="button" data-toggle="modal" id="11" class="push">Read more</a>
<script>
$(document).ready(function () {
$('.push').click(function () {
var res_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: '../php-files/resolve.php', // in here you should put your query
data: 'post_id=' + res_id, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success: function (r) {
// now you can show output in your modal
$('#mymodal').modal('show'); // put your modal id
$('.modal-body').show().html(r);
}
});
});
});
</script>
<!-- Modal -->
<div id="myModal" class="modal hide fade in" 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">Modal Header</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

In success function add this code
$('#id1').modal('show'); // you
$('#body').html(r);
Your model should be as below
<div class="modal" id="id1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
...
<div id="body" class="modal-body text-center">
<!-- loading modal.. -->
</div>
..
</div>

Related

Performance and Optimization - Too many bootstrap modals

I am building a table based on data returned from my API.
For each row in the table I would like to create a bootstrap modal with additional info in it.
This is how I do it right now. I created a designated div and I put all the modals inside it. Please note that in addition the modal's HTML is pretty big by itself:
let modal = `<div id="modal-${i}">big HTML here</div>`;
$("#modalsCollector").append(modal);
And this is how my table row looks like:
<tr data-toggle="modal" data-target="#modal-${i}">
Because I sometimes have 500+ table rows there is eventually a huge div (#modalsCollector) full of same (by structure) modals. I feel that it affects page performance.
Is there a better, more elegant and performance optimized way to bind modals to table rows? Or in general, working with many hidden elements instead of pushing them into the DOM that way?
You can include only one "null" modal in your <body>, like this:
<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>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Then when you have to show the modal generate it using jQuery like this:
$("#button").click(function(e){
$("#myModal .modal-header").append(HTML for modal header here);
$("#myModal .modal-body").html(big HTML for modal body here);
$("#myModal").modal("show");
});
So, basically you change the modal header and the modal body of the same modal each time, with the needed information accordingly, without the need of like thousands of modals.
Bootstrap has a neat way of changing the components of the same modal. This is as long as you need the same modal just different content inside.
https://getbootstrap.com/docs/4.5/components/modal/#varying-modal-content
Here is an example:
HTML:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#mdo">Open modal for #mdo</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#fta">Open modal for #fat</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
and jQuery:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// Update the modal's content.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})

Display Bootstrap Modal using javascript onClick

How do I add a bootstrap modal in the the javascipt on click. So far I was only able to alert ("hello") on click. How do i prompt out a modal box?
graph.on("click", function (params) {
var node = params['nodes'][0];
displayInfo=false;
if(node!=null){
console.log('node:'+ params['nodes'][0]);
x = params["pointer"]['canvas']['x'];
y = params["pointer"]['canvas']['y'];
displayInfo=true;
lastNode = nodes.get(node);
lastClick = params['pointer'];
//console.log(node);
}
alert("hello");
//add boostrap modal here
});
You don't need an onclick.
<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
If you need an onclick event anyhow, use it like below:
graph.on("click", function (params) {
$('#myModal').modal('show');
}
Reference: http://getbootstrap.com/javascript/#modals
Create modal HTML and assign id for it, for example "my_modal"
http://getbootstrap.com/javascript/#live-demo
show the modal at the js using the code:
$("#my_modal").modal('show');
First make the modal pop up div then , Configure and use .modal('show')
For eg:-
You can also use onClick call for jquery here.
<div id="modalDiv">
//some content
</div>
In jquery use ,
$("#modalDiv").modal('show');
Check this http://getbootstrap.com/javascript/#live-demo
You can use id like
$("#modal-id").modal("show");
Or you can use class name $(".modal-class").modal("show");

Laravel - How to reuse modal code and open different modals according to button click

So I have a few buttons that open the same modal but different content. I don't want to copy/paste the modal code each time I need to open a new model. I want to use the same modal code and according to the button clicked load different content in the modal. How can I do that?
Here is my modal code:
<div class="dialogs-holder">
<div class="dialog new_file">
<div class="dialog-header clearfix">
<a class="flaticon stroke maximize-4" href="/"></a>
<div class="dialog-title"><span class="gray-bckg">{{ //different according to button }}</span></div>
<div class="flaticon stroke x-1"></div>
</div>
<div class="dialog-content clearfix">
#include('includes.modals.' . //different template according to button )
</div>
</div>
</div>
How can I do that?
You have to use the javascript to do that.
first you have handle the each event when the buttons are clicked. then you can set the content by dynamically to the title and content of modal using javascript.
eg.
// give the id to title tag of modal
<span class="gray-bckg" id="modal_title"></span>
//give the id to content tag of modal
<div class="dialog-content clearfix" id="content"></div>
now add the script
//with script
$("#button1").on("click",function(e){
$("#content").val("this is button1 content");
$(".modal").open();
});
$("#button2").on("click",function(e){
$("#content").val("this is button2 content");
$(".modal").open();
});
It's a late answer and adapted for Laravel but it might interest someone.
I created a modal.blade.php
<div id="{{ $id or 'modal' }}" class="modal fade" role="dialog">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header text-center">
<h2>{{ $title }}</h2>
</div>
<div class="modal-body">
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</div>
And now when I want to pop-up a modal I use this
#component('whereyourmodalisplaced.modal', [
'id' => 'task-show', //If you use multi modal on same page, always use ID
'title' => 'Edit a task'])
#endcomponent
I'm updating the modal contact with ajax when needed with this kind of behaviour
<a href=""
data-endpoint="{{ route('tasks.show' , ['tasks' => $task->id]) }}"
data-target="task-show .modal-content .panel-body"
data-modal="task-show"
data-cache="false"
data-async="true"
data-toggle="modal" >{{ $task->name }}</a>
And make sure to always have this in your code
$('body').on('click', 'a[data-async="true"]', function(e)
{
e.preventDefault();
var self = $(this),
url = self.data('endpoint'),
target = self.data('target'),
modal = self.data('modal');
$.ajax({
url: url,
type: self.data('method'),
cache : self.data('cache'),
success: function(data)
{
if (target !== 'undefined'){ $('#'+target).html( data ); }
if (modal !== 'undefined'){ $('#'+modal).modal( 'show' ); }
}
});
});
follow bellow steps and you will got output which near your requirements.
Step 1. Create Routes like bellow in routes.php
Route::get('test_model1',['as'=>'test_model1', 'uses'=>'TestController#test_model1']);
Route::get('test_model2',['as'=>'test_model2', 'uses'=>'TestController#test_model2']);
Step 2. Setup Testcontroller with bellow code in Testcontroller.php
class TestController extends Controller {
public $param=array();
public function __construct(){
//$this->middleware('auth');
}
public function test_model1(){
$this->param['content']="Model 1 body.";
return view('test.model',$this->param);
}
public function test_model2(){
$this->param['content']="Model 2 body.";
return view('test.model',$this->param);
}
}
Step 3. setup model body content view. in resources/test/model.blade.php
<div class="row">
<div class="col-xs-12">
<p><?php echo $content; ?></p>
</div>
</div>
Step 4. setup bello code in any of your view file.
<a href="<?php echo route('test_model1'); ?>" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-primary">
Launch Modal 1
</a>
<a href="<?php echo route('test_model2'); ?>" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-danger">
Launch Modal 2
</a>
<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-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
</script>

jQuery .load() bootstrap modal and show

I am trying to .load() a bootstrap modal in my page and show it immediately. Below is the code I have written (which isn't working as the modal opens but can then never be closed)!
Basically I am trying to .load() a list of players in a modal when you click on a team name (with the class .team), I've tried various ways of calling $($this).empty() with no success.
Here is my function:
$(function () {
$('.team').on('click', function () {
var target = $(this).data('target');
$('#results-modals').load('/team-players.html ' + target, function (response, status, xhr) {
if (status === "success") {
$(target).modal({ show: true });
}
});
});
});
Here is the html anchor and example modal:
<a class='team' data-toggle='modal' data-target='#20'>Real Madrid</a>
Data held in external file team-players.html:
<div id='20' class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<p>Player 1: Ronaldo</p>
</div>
</div>
</div>
$(function(){
var url = "url of the modal window content";
$('.my-modal-cont').load(url,function(result){
$('#myModal').modal({show:true});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Modal Window Container -->
<div class="my-modal-base">
<div class="my-modal-cont"></div>
</div>
<!-- Modal Window content -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>My modal content here…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Instead of $($this).modal({ show: true }); try $(this).modal('show');
To hide the modal, you can use $(this).modal('hide');
You can do $(this).modal("toggle") if it open it will close and vice versa.
jQuery .load() bootstrap modal and show
for show $(#ID).modal('show');
for hide $(#ID).modal('hide');

Jquery + Bootstrap Modal, open a modal inside the other... why?

I'm trying to load the data from ajax inside a bootstrap modal like this:
function edit_company_modal(id){
$.get('/panel/companies/edit/'+id+'/', function(data) {
$('#editCompanyModal').modal('show');
$('#editCompanyModal').html(data);
}
);
return false;
}
But what is happen is that it is trying to open a modal inside the other, and nothing is show... but the response is right (checked at firebug)
that is how it looks after click event:
<div class="modal fade in" id="editCompanyModal" aria-labelledby="Edit Company" aria-hidden="false" style="display: block;">
<div class="modal fade" id="editCompanyModal" aria-labelledby="Edit Company" aria-hidden="true">
How should I do something like that?
Thanks
You need to insert the data into the modal's body container.Since we don't have your HTML let's take a general modal structure and apply the jQuery to fill the modal's body after the ajax call. Notice since you are using data-target for the button element, you no longer need to use the .modal('show')
HTML
<button id="editCompany" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#editCompanyModal">Launch demo modal</button>
<div class="modal fade" id="editCompanyModal" tabindex="-1" role="dialog" aria-labelledby="editCompanyModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<h3>Modal Body</h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
jQuery
$('#editCompany').click(function() {
//Get value of id
// id = ???
$.ajax({
url: '/panel/companies/edit/'+id+'/',
type: 'GET',
success: (data, status, xhr) ->
$('#editCompanyModal .modal-body').html(data);
});
});

Categories

Resources