Jquery - Sortable did not work when div.load is called - jquery-ui-sortable

I have this issue that every time the div is loaded using div.load in the ajax success, the code for sortable will not work. Sortable will work again after the page is refreshed manually. What could be the possible solution for this?
$(document).on('click', '#add-song-tag', function() {
tag_id = $('#tags').val();
$.ajax({
url: base_url + '/songtags/add_song_tag',
type: 'POST',
data: {
song_info_id: song_info_id,
tag_id: tag_id
},
success: function() {
$('#category').load(window.location.href + ' #category');
$('#modal-categories').trigger('change');
},
error: function(xhr) {
console.log(xhr.responseText);
}
})
});
I have my code in the sortable.js like
$( function() {
$( "#sortable, #sortable1" ).sortable({
connectWith: ".draggable-group",
start: function(event, ui){
$(ui.item).width($('#sortable div').width());
}
// containment: "parent",
// tolerance: "pointer"
}).disableSelection();
} );
and in the html it looks something like:
<?php if($selected_tag_for_m['category_id'] == $tempo_id):?>
<div class="btn-group draggable-group">
<div>
<i class="fa fa-minus-circle fa-lg delete-a-tag" aria-hidden="true"></i>
</div>
<div type="button" class="btn btn-default btn-color"><i class="fa fa-circle-o custom-text-blue"></i> <?php echo $selected_tag_for_m['tag_name'];?> </div>
<div type="button" class="btn btn-default custom-bgcolor-blue dropdown-toggle" data-toggle="dropdown">
<span><i class="fa fa-pencil"></i></span>
<span class="sr-only">Toggle Dropdown</span>
</div>
<ul class="dropdown-menu" role="menu" id="tempo">
<?php foreach($tempos as $tempo):?>
<li data-id="<?php echo $selected_tag_for_m['info_tag_id']?>"><a href="" data-id="<?php echo $tempo['tag_id']?>" class="songtaglist" ><?php echo $tempo['tag_name'];?></a></li>
<?php endforeach;?>
</ul>
</div>
<?php endif;?>

I found solution to this by calling sortable.js script in body of the load function. The code looks like this:
$('#category').load(window.location.href + ' #category', function(){
$.getScript(base_url + '/assets/js/sortable.js');
});

Related

Semantic UI Custom Rule Validation for Select Drop-Down Field

I am trying to add some custom logic to my semantic ui validation but can't figure out what I am doing wrong.
Basically, when the user selects "Yes" from the drop-down, I would like to make the "input_field" mandatory. If the user selects "No", the "input_field" becomes optional and the form can be submitted.
I tried searching for examples and followed some code from the Semantic Ui website but can't figure out what I am missing. Any advice would be appreciated as I am on a deadline for a project I am working on.
Form:
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
Validation:
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
},
input_field: {
identifier: 'input_field',
depends: 'select',
rules: [
{
type: 'empty',
prompt: function() {
$('.select').on('change', function() {
if( this.value == 'Yes') {
return "Custom Validation";
}
return false;
}).trigger("change");
}
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
});
</script>
Figured out a solution for this! It might not be the best answer but it works and does what I am looking for.
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
$('.selectOption').on('change', function() {
if ( this.value == 'Yes' ) {
$('.ui.form').form('add rule', 'input_field', ['empty', 'integer']);
$('.ui.form').form('add prompt', 'input_field', 'Enter an integer');
}
if ( this.value == 'No' ) {
$('.ui.form').form('remove prompt', 'input_field');
$('.ui.form').form('remove rule', 'input_field');
}
}).trigger("change");
});
</script>
I was able to implement the validation rule by extending Semantic UI setting rules.
See below example:
$.fn.form.settings.rules.dependsOnFieldValue = function (value, dependFieldValue) {
var identifier = dependFieldValue.split('[')[0];
var dependValue = dependFieldValue.match(/\[(.*)\]/i)[1];
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? !( dependValue.toString() === matchingValue.toString() && value === '')
: false
;
};
Then in the form validation initializer you will pass the desired values as below:
$(".ui.form").form({
fields: {
select: {
identifier: 'select',
rules : [
{
type : 'empty'
}
]
},
input_field: {
identifier : 'input_field',
rules : [
{
type : 'dependsOnFieldValue[select[Yes]]',
}
]
},
...
}
});
Notice that we pass the <select> identifier (in this case also called select) within the first [] and then the value that we want to see to make the input_field mandatory ("Yes" in this case).

How to create mysql table entry on form submission in CodeIgniter

I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}

angularfire and facebook login getting Cannot read property 'onAuth' of undefined

Hi i found a sample of auth on routing with angularfire, i just change it to support the new firebase sdk v4 and still using angularfire v1.
this is the link of the piece of code i used (with ui-router) :
angularfire docs
now this is my app.js and index.html
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForAuth();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
})
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="$parent.auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="$parent.auth.$unauth()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.3/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
</body>
</html>
now the problem is that i getting an error : Cannot read property 'onAuth' of undefined.
i think its problem of the version of the new SDk and i looked in the proposed solution here in stackoverflow but none of them fix me the problem.
please help...
Ok i figure out the problem and fix it by changing the versions of angular and angularfire. and a little change to migrate to the new sdk.
this is new code.
my problem now is that i don't get all the scope that i want from facebook. for example i want birthday and i cannot see it comes back.
someone have a suggestion ?
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
//var provider = Auth.FacebookAuthProvider();
//provider.addScope('user_birthday');
//
//Auth.signInWithRedirect(provider);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForSignIn();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
});
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.currentUser = null;
$scope.currentUserRef = null;
$scope.currentLocation = null;
$scope.auth = Auth;
console.log(Auth);
/**
* Function called when clicking the Login/Logout button.
*/
// [START buttoncallback]
$scope.SignIn = function () {
if (!Auth.currentUser) {
$scope.auth.$signInWithRedirect('facebook', {
scope: 'email, public_profile, user_birthday'
}).then(function (authData) {
// never come here handle in $onAuthStateChanged because using redirect method
}).catch(function (error) {
if (error.code === 'TRANSPORT_UNAVAILABLE') {
$scope.$signInWithPopup('facebook', {
scope: 'email, public_profile, user_friends'
}).catch(function (error) {
console.error('login error: ', error);
});
} else {
console.error('login error: ', error);
}
});
} else {
// [START signout]
Auth.signOut();
// [END signout]
}
};
// [END buttoncallback]
//
// $scope.updateUserData = function () {
// $scope.currentUserRef.set($scope.currentUser);
// };
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log('after login');
console.log($scope.authData);
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="SignIn()">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
</body>
</html>

Open bootstrap modal with vue.js 2.0

Does anyone know how to open a bootstrap modal with vue 2.0? Before vue.js I would simply open the modal by using jQuery: $('#myModal').modal('show');
However, is there a proper way I should do this in Vue?
Thank you.
My code is based on the Michael Tranchida's answer.
Bootstrap 3 html:
<div id="app">
<div v-if="showModal">
<transition name="modal">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" #click="showModal=false">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
modal body
</div>
</div>
</div>
</div>
</div>
</transition>
</div>
<button id="show-modal" #click="showModal = true">Show Modal</button>
</div>
Bootstrap 4 html:
<div id="app">
<div v-if="showModal">
<transition name="modal">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" #click="showModal = false">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" #click="showModal = false">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</transition>
</div>
<button #click="showModal = true">Click</button>
</div>
js:
new Vue({
el: '#app',
data: {
showModal: false
}
})
css:
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
display: table;
transition: opacity .3s ease;
}
.modal-wrapper {
display: table-cell;
vertical-align: middle;
}
And in jsfiddle
Tried to write a code that using VueJS transitions to operate native Bootsrap animations.
HTML:
<div id="exampleModal">
<!-- Button trigger modal-->
<button class="btn btn-primary m-5" type="button" #click="showModal = !showModal">Launch demo modal</button>
<!-- Modal-->
<transition #enter="startTransitionModal" #after-enter="endTransitionModal" #before-leave="endTransitionModal" #after-leave="startTransitionModal">
<div class="modal fade" v-if="showModal" ref="modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button class="close" type="button" #click="showModal = !showModal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button class="btn btn-secondary" #click="showModal = !showModal">Close</button>
<button class="btn btn-primary" type="button">Save changes</button>
</div>
</div>
</div>
</div>
</transition>
<div class="modal-backdrop fade d-none" ref="backdrop"></div>
</div>
Vue.JS:
var vm = new Vue({
el: "#exampleModal",
data: {
showModal: false,
},
methods: {
startTransitionModal() {
vm.$refs.backdrop.classList.toggle("d-block");
vm.$refs.modal.classList.toggle("d-block");
},
endTransitionModal() {
vm.$refs.backdrop.classList.toggle("show");
vm.$refs.modal.classList.toggle("show");
}
}
});
Example on Codepen if you are not familiar with Pug click View compiled HTML on a dropdown window in HTML section.
This is the basic example of how Modals works in Bootstrap. I'll appreciate if anyone will adopt it for general purposes.
Have a great code 🦀!
I did an amalgam of the Vue.js Modal example and the Bootstrap 3.* live demo.
Basically, I used the Vue.js modal example but replaced (sorta) the Vue.js "html" part with the bootstrap modal html markup, save one thing (I think). I had to strip the outer div from the bootstrap 3, then it just worked, voila!
So the relevant code is regarding bootstrap. Just strip the outer div from the bootstrap markup and it should work. So...
ugh, a site for developers and i can't easily paste in code? This has been a serious continuing problem for me. Am i the only one? Based on history, I'm prolly an idiot and there's an easy way to paste in code, please advise. Every time i try, it's a horrible hack of formatting, at best.
i'll provide a sample jsfiddle of how i did it if requested.
Using the $nextTick() function worked for me. It just waits until Vue has updated the DOM and then shows the modal:
HTML
<div v-if="is_modal_visible" id="modal" class="modal fade">...</div>
JS
{
data: {
isModalVisible: false,
},
methods: {
showModal() {
this.isModalVisible = true;
this.$nextTick(() => {
$('#modal').modal('show');
});
}
},
}
Here's the Vue way to open a Bootstrap modal..
Bootstrap 5 (2022)
Now that Bootstrap 5 no longer requires jQuery, it's easy to use the Bootstrap modal component modularly. You can simply use the data-bs attributes, or create a Vue wrapper component like this...
<bs-modal id="theModal">
<button class="btn btn-info" slot="trigger"> Bootstrap modal </button>
<div slot="target" class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</bs-modal>
const { Modal } = bootstrap
const modal = Vue.component('bsModal', {
template: `
<div>
<slot name="trigger"></slot>
<slot name="target"></slot>
</div>
`,
mounted() {
var trigger = this.$slots['trigger'][0].elm
var target = this.$slots['target'][0].elm
trigger.addEventListener('click',()=>{
var theModal = new Modal(target, {})
theModal.show()
})
},
})
Bootstrap 5 Modal in Vue Demo
Bootstrap 4
Bootstrap 4 JS components require jQuery, but it's not necessary (or desirable) to use jQuery in Vue components. Instead manipulate the DOM using Vue...
Launch modal
<div :class="modalClasses" class="fade" id="reject" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal</h4>
<button type="button" class="close" #click="toggle()">×</button>
</div>
<div class="modal-body"> ... </div>
</div>
</div>
</div>
var vm = new Vue({
el: '#app',
data () {
return {
modalClasses: ['modal','fade'],
}
},
methods: {
toggle() {
document.body.className += ' modal-open'
let modalClasses = this.modalClasses
if (modalClasses.indexOf('d-block') > -1) {
modalClasses.pop()
modalClasses.pop()
//hide backdrop
let backdrop = document.querySelector('.modal-backdrop')
document.body.removeChild(backdrop)
}
else {
modalClasses.push('d-block')
modalClasses.push('show')
//show backdrop
let backdrop = document.createElement('div')
backdrop.classList = "modal-backdrop fade show"
document.body.appendChild(backdrop)
}
}
}
})
Bootstrap 4 Vue Modal Demo
My priority was to keep using Bootstrap code, since they made the effort to make the modal work, fixin' the scrollbars and all. I found existing proposals try to mimic that, but they go only part of the way. I didn't even want to leave it to chance: I just wanted to use actual bootstrap code.
Additionally, I wanted to have a procedural interface, e.g. calling dialog.show(gimme plenty of parameters here), not just toggling a variable somewhere (even if that variable could be a complex object).
I also wanted to have Vue's reactivity and component rendering for the actual dialog contents.
The problem to solve was that Vue refuses to cooperate if it finds component's DOM to have been manipulated externally. So, basically, I moved the outer div declaring the modal itself, out of the component and registered the component such that I also gain procedural access to the dialogs.
Code like this is possible:
window.mydialog.yesNo('Question', 'Do you like this dialog?')
On to the solution.
main.html (basically just the outer div wrapping our component):
<div class="modal fade" id="df-modal-handler" tabindex="-1" role="dialog" aria-hidden="true">
<df-modal-handler/>
</div>
component-template.html (the rest of the modal):
<script type="text/x-template" id="df-modal-handler-template">
<div :class="'modal-dialog ' + sizeClass" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" v-html="body"/>
<div class="modal-footer">
<button type="button" v-for="button in buttons" :class="button.classes" v-bind="button.arias"
#click.stop="buttonClick(button, callback)">{{ button.text }}
</button>
</div>
</div>
</div>
</script>
component-def.js - contains logic for showing & manipulating the dialog, also supports dialog stacks in case you make a mistake and invoke two dialogs in sequence:
Vue.component('df-modal-handler', {
template: `#df-modal-handler-template`,
props: {},
data() {
return {
dialogs: [],
initialEventAssignDone: false,
};
},
computed: {
bootstrapDialog() { return document.querySelector('#df-modal-handler'); },
currentDialog() { return this.dialogs.length ? this.dialogs[this.dialogs.length - 1] : null; },
sizeClass() {
let dlg = this.currentDialog;
if (!dlg) return 'modal-sm';
if (dlg.large || ['large', 'lg', 'modal-lg'].includes(dlg.size)) return 'modal-lg';
else if (dlg.small || ['small', 'sm', 'modal-sm'].includes(dlg.size)) return 'modal-sm';
return '';
},
title() { return this.currentDialog ? this.currentDialog.title : 'No dialogs to show!'; },
body() { return this.currentDialog ? this.currentDialog.body : 'No dialogs have been invoked'; },
callback() { return this.currentDialog ? this.currentDialog.callback : null; },
buttons() {
const self = this;
let res = this.currentDialog && this.currentDialog.buttons ? this.currentDialog.buttons : [{close: 'default'}];
return res.map(value => {
if (value.close == 'default') value = {
text: 'Close',
classes: 'btn btn-secondary',
data_return: 'close'
};
else if (value.yes == 'default') value = {
text: 'Yes',
classes: 'btn btn-primary',
data_return: 'yes'
};
else if (value.no == 'default') value = {
text: 'No',
classes: 'btn btn-secondary',
data_return: 'no'
};
value.arias = value.arias || {};
let clss = (value.classes || '').split(' ');
if (clss.indexOf('btn') == -1) clss.push('btn');
value.classes = clss.join(' ');
return value;
});
},
},
created() {
// make our API available
window.mydialog = this;
},
methods: {
show: function show() {
const self = this;
if (!self.initialEventAssignDone) {
// created is too soon. if we try to do this there, the dialog won't even show.
self.initialEventAssignDone = true;
$(self.bootstrapDialog).on('hide.bs.modal', function (event) {
let callback = null;
if (self.dialogs.length) callback = self.dialogs.pop().callback;
if (self.dialogs.length) event.preventDefault();
if (callback && callback.df_called !== true) callback(null);
});
}
$(self.bootstrapDialog).modal('show');
},
hide: function hide() {
$(this.bootstrapDialog).modal('hide');
},
buttonClick(button, callback) {
if (callback) { callback(button.data_return); callback.df_called = true; }
else console.log(button);
this.hide();
},
yesNo(title, question, callback) {
this.dialogs.push({
title: title, body: question, buttons: [{yes: 'default'}, {no: 'default'}], callback: callback
});
this.show();
},
},
});
Do note that this solution creates one single dialog instance in the DOM and re-uses that for all your dialog needs. There are no transitions (yet), so the UX isn't too great when there are multiple active dialogs. It's bad practice anyway, but I wanted it covered because you never know...
Dialog body is actually a v-html, so just instantiate your component with some parameters to have it draw the body itself.
I create button with params for modal and simply trigger click()
document.getElementById('modalOpenBtn').click()
<a id="modalOpenBtn" data-toggle="modal" data-target="#Modal">open modal</a>
<div class="modal" id="Modal" tabindex="-1" role="dialog" aria-labelledby="orderSubmitModalLabel" aria-hidden="true">...</div>
From https://getbootstrap.com/docs/4.0/getting-started/javascript/#programmatic-api
$('#myModal').modal('show')
You can do this from a Vue method and it works just fine.
modal doc
Vue.component('modal', {
template: '#modal-template'
})
// start app
new Vue({
el: '#app',
data: {
showModal: false
}
})
<script type="text/x-template" id="modal-template">
<transition name="modal">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
<div class="modal-header">
<slot name="header">
default header
</slot>
</div>
<div class="modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
default footer
<button class="modal-default-button" #click="$emit('close')">
OK
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
</script>
<!-- app -->
<div id="app">
<button id="show-modal" #click="showModal = true">Show Modal</button>
<!-- use the modal component, pass in the prop -->
<modal v-if="showModal" #close="showModal = false">
<!--
you can use custom content here to overwrite
default content
-->
<h3 slot="header">custom header</h3>
</modal>
</div>

zend framework partial not render echo on ajax request

I'd like to render a partial as a response to an ajax request in my controller action.
My goal is to echo a Twitter Bootstrap Alert when ajax request is successful.
Here is my action (redigeraLottningAction):
if($this->getRequest()->isXmlHttpRequest()){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
echo $this->view->partial('partial/alert-ajax.phtml', array('type' => 'success', 'msg' => 'Lyckat! Lottningen är nu sparad.'));
}
And my partial (alert-ajax.phtml):
<div id="alert-msg" class="alert alert-<?= $this->type?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?= $this->msg?></p>
</div>
The problem is that the php scripts in the partial is outputed as text. This is what it looks like in the browser with variables not rendered:
<div id="alert-msg" class="alert alert-<?= $this->type?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?= $this->msg?></p>
</div>
And the jquery part:
$(document).ready(function(){
$('#lottning-spara').click(function () {
$.ajax({
type: "POST",
url: '/turnering/redigera-lottning',
cache: false,
data: {id: getParam("turnering"), klass_id: getParam("klass"), type: "spara", lottning: $('#lottning_str').val()},
dataType: 'html',
success: function(msg){
$('#alert-div').html(msg);
},
error: function(){
$('#alert-div').html('Error!');
}
});
});
});
Any ideas why the php in partial is not rendered??
Edits are bold.
Problem Solved.
The alert-ajax.phtml file was a different charset type.
What if you try this:
<div id="alert-msg" class="alert alert-<?php echo $this->type; ?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?php echo $this->msg; ?></p>
</div>
if($this->getRequest()->isXmlHttpRequest()){
$this->view->assign(array('type' => 'success', 'msg' => 'Lyckat! Lottningen är nu sparad.'));
echo $this->view->render('partial/alert-ajax.phtml');
exit;
}
Problem Solved. The alert-ajax.phtml file was a different charset type.