I'm new to modal show-up bootstrap. please someone help me.. my problem is how to fetch my table data's dynamically and display it to the modal content when the button modal click.. I tried searching but i can't get on how to do it perfectly..
my code is below:
Please someone help me... What should I use??
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="../js/js/bootstrap.min.js"></script>
<link href="../js/js/bootstrap.min.css" rel="stylesheet" >
<script type="text/javascript">
$(function () {
$("#btnShow").click(function(){
$('#demoModal').modal('show');
});
});
</script>
<div>
<button id="btnShow">Chapter</div>
<!-- Modal -->
<div class="modal fade" id="demoModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<h4 class="modal-title" id="myModalLabel">Chapter List</h4>
</div>
<div class="modal-body">
<!-- the possible data that should be fetch -->
<?php
$con=mysqli_connect("localhost","root","","scenezone");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT chapter_title FROM story_chapter
WHERE story IN (SELECT story FROM story_chapter WHERE status = '1');";
$result=mysqli_query($con,$sql);
// Fetch all
$i = 0;
while($row = mysqli_fetch_array($result)){
if ($i % 5 == 0) {
echo "<tr>";
}
echo "<td><p>".$row["Chapter"]."</p>
</td>";
if ($i % 5 == 4) {
echo "</tr>";
}
$i++;
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
</div>
Assuming that you are working on a very basic level with simple php files in work. The data that you need to show should be in a .php file lets say chapters.php, and you should call that file using ajax when the bootstrap modal is shown by clicking a button.
I assume you have the default html structure for the bootstrap modal with the modal-body class for the body section.
Now bootstrap modal have events that can be used for this purpose you can use
bs.shown.modal fired just before the modal is open.
Bind the event like below
$('#demoModal').on('show.bs.modal', function() {
$.ajax({
url: 'chapters.php',
method: 'get',
success: function(data) {
$(".modal-body").html(data);
},
error:function(xhr,code,text){
alert("error occoured : "+text);
}
});
});
Related
I want a box with a welcome message etc to appear after a user registrers on my website. But instead of making it appear from just clicking on a button, i want it to happend when the email,password,username etc gets sendt to the database. So, instead of doing this :
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button>
Is there any ways i can do this programmatically? I have also tried :
<script>
self = function(id01)
</script>
but it wont work. Any tips on what i should try/ do?
This is how i send the info to my database :
//if no errors have been created carry on
if(!isset($error)){
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
$activasion = md5(uniqid(rand(),true));
try {
$stmt = $db->prepare('INSERT INTO members (username,password,email,active) VALUES (:username, :password, :email, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at Game World.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
?>
well you can achieve what the results you want in many ways, js alerts, jquery pop up. bootstrap modals.
Option 1 :
using jquery and jquery ui
<!-- latest stable jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- latest stable jquery ui -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<div id="modal" style="display: none;">
This is pop up, add message.
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#modal").dialog();
});
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
Option 2 :
Using Bootstrap
<!-- latest stable jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap links -->
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<div class="modal fade" id="success">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="alert alert-block alert-success">
<h4>Welcome</h4>
<p>Add Message</p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('document').ready(function(){
$('#success').modal('toggle'); });
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
Option 3
Js alert
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<script type="text/javascript">
alert('welcome');
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
The first option, you will need to style the pop/div according to your design needs.
as you can see u need to first check if the action in the url is joined, meaning they have successfully signed up, then show the popup
You can do this using server side language PHP using $_GET['action'] or $_REQUEST['action'] on a proper return of your header - index.php?action=joined
Create logic on your DB insert page that checks to see if your query was successful. On success, it routes you to the header redirect, else returns an error message and exits the script.
Something like this:
$query = 'INSERT INTO members (username,password,email,active) VALUES (:username, :password, :email, :active)';
$stmt = $db->prepare($query);
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
//Check to see if your $stmt is set, will return true if successful else it will return false
if($stmt){
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at Game World.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
}else{
echo 'Sorry but there was an issue with the INSERT.';
exit();
}
On index.php use an if/else statement or switch to check if $_GET['action'] (isset) and see if it is == to your value 'joined'. Then create a variable to hold your welcome message and display it else declare the variable null or post an alternate message perhaps.
Top of your index.php page:
$message = "";
if(isset($GET['action']) && $GET['action']=="joined"){
//place your Welcome message here
$message .= "<h2>Welcome and thank you for signing up!</h2>";
}else{
$message .= "<h2>Some other message</h2>";
//Or you could go with empty quotes or declare $message NULL
}
Then in your HTML call on your variable $message with something like:
<?=$message?> or <?php echo $message; ?>
<body>
<div id='wrapper'>
<header>Some header</header>
<nav id='nav'>
<ul>
<li class="nav-item">
BUTTON 1
</li>
<li class="nav-item">
BUTTON 2
</li>
</ul>
</nav>
<div id="content">
<?=$message?>
<div id="heading">Some Page Heading</div>
<div id="">
<p>
Some page content.
</p>
</div>
</div>
</div>
</body>
I am not the most proficient in PHP but this is probably how I would handle a server side request like this.
*** Keep in mind that you are requesting an update to your page on the update of your server, not a client side action like pressing the button.
Hope this helps.
I have tried to find this out here and not found what I was looking for.
The Goal: After a process has completed, to display a Bootstrap Modal that notifies the user it is complete (and/or that the admin may need to authorize something, for example, a comment may need to be authorized ...).
I can output a JavaScript script (sounds redundant as I type that) that will open the modal, but I want to pass text to the modal so I can have a reusable dialog. Here's the basic code I am working with:
The modal form:
<!-- language: lang-html -->
<!-- meant to be an alert dialog -->
<div id="myAlert" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" 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>
<h3 class="modal-title" id="descModalLabel"></h3>
</div> <!-- / modal-header -->
<div class="modal-body">
<!-- some text will be inserted here -->
</div><!-- / modal-body -->
<div class="modal-footer" -->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div><!-- / modal-footer -->
</div><!-- / modal-content -->
</div><!-- /modal-dialog -->
</div> <!--/ modal -->
<!-- end of modal form -->
<!-- end snippet -->
The JavaScript to open the form:
// for the myAlert modal:
// code to open the modal with the caption and description:
$('#myAlert').on('show.bs.modal', function (event)
{
var modal = $(this);
// need to get these values passed somehow
var caption = "Test";
var description = "Test Test Test";
modal.find('.modal-title').text( caption );
modal.find('.modal-body').append( '<strong>Description:</strong> ' + description );
});
// when modal closes, clear out the body:
$('#myAlert').on('hidden.bs.modal', function ()
{
$(this).find(".modal-body").text('');
});
The PHP that outputs the script that actually opens it:
echo '<script>';
// how do I pass the variables???
echo '$("#myAlert").modal("show")';
echo '</script>';
I would like to be able to pass the caption and description values to the form, but cannot figure it out. I have a version that works with a button based heavily on the Bootstrap site, but I cannot figure this one out. Thanks in advance!
There are probably better solutions out there but this one works too as I have tested already. It requires to take 3 steps:
You need to declare your variables you want to pass to JavaScript above all events and functions (make them global).
For example:
var global_caption = "Some default caption";
var global_description = "Some default description";
// All scripts now go here
In your modal you assign local variables from global variables (or use global variables directly) for some events, for example:
This will show basically the same thing as in your case so far:
$('#myAlert').on('show.bs.modal', function (event)
{
var modal = $(this);
var caption = global_caption;
var description = global_description;
modal.find('.modal-title').text( caption );
modal.find('.modal-body').append( '<strong>Description:</strong> ' + description );
});
With echo you assign new values to global variables and summon the event again.
Declaration can go as simply as:
echo '<script>';
echo 'global_caption = "This is a new caption"';
echo 'global_description = "This is a new description"';
echo '$("#myAlert").modal("show")';
echo '</script>';
I've got some code that is loaded on my footer via jquery (So that every page visited has the code on its page)
This code is meant to check a database and, if any responses, send a bootstrap modal to the client. When the modal is sent, the row is deleted from the database. Each user has their own row in the database when an update happens.
The footer code is reloaded every 10 seconds to check if there are any updates to the relative table.
This works, except even after the row is deleted, PHP seems to execute code inside my if blocks that shouldn't be executeted, as it is causing the modal to close or pile up on top of eachother, forcing the client to reload their page to continue browsing.
So lets say a client loads the index page, and they have a pending message waiting for them.
The modal is sent for the user to close manually. If the user waits more than 10 seconds, the modal will close itself but the backdrop will remain, making it so the user cannot click anything until the page is reloaded. If the user waits another 10 seconds, another backdrop is added, darkening the screen. This goes on and on until the screen is completely black or the client reloads the page.
The code that opens the modal is inside of 2 if blocks basically stating that it should not be executed.
Here is my reloading code:
<?
include("dbConnect.php");
$sql = "SELECT DISTINCT Message,uniqueID from sendMessage WHERE UserID='".$_GET['userID']."';";
$ret = $db->query($sql);
$loop = 0;
$messages = array();
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$loop++;
array_push($messages,array("uniqueID" => $row['uniqueID'], "Message" => $row['Message']));
}
if($loop != 0) {
if(!empty($messages)) {
?>
<script type="text/javascript">
$(document).ready(function () {
$('.modal').modal('hide');
$('#memberModal').modal('show');
});
</script>
<!-- Modal -->
<div class="modal fade" id="memberModal" tabindex="-1" role="dialog" aria-labelledby="memberModalLabel">
<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="memberModalLabel">Message from Administrators</h4>
</div>
<div class="modal-body">
<?
foreach($messages as $v) {
echo $v['Message'];
if($loop > 1) {
echo "<br><br>";
}
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?
foreach($messages as $v) {
$sql2 = "DELETE from sendMessage where uniqueID='".$v['uniqueID']."';";
$ret2 = $db->exec($sql2);
}
}
}
?>
As far as I can tell, all the imports are correct (Otherwise the modal wouldn't work at all, right?)
Here is the jquery in my footer:
<div id="links"></div>
<script>
function loadlink(){
$('#links').load('templates/sendMessage.php?userID=<?=$userInfo['uniqueid'];?>',function () {});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 10000);
</script>
--edit--
I suspect my issue is because the div is reloaded again while the modal is open, therefore breaking it because it is erasing the code the modal is in. I'm not sure how to combat this.
The code is not complete, but from what I can tell your ajax script should only send the content of the modal, not the whole modal, append() it in (or use html() if you want to remove the previous messages) <div class="modal-body"> and then show the modal. Now you are inserting the whole modal code inside the modal and get a babushka effect.
-- EDIT --
In your php script, return only the messages, not the modal html:
[...]
if($loop != 0) {
if(!empty($messages)) {
foreach($messages as $v) {
echo $v['Message'];
if($loop > 1) {
echo "<br><br>";
}
}
[...]
The in the footer
<!-- Modal -->
<div class="modal fade" id="memberModal" tabindex="-1" role="dialog" aria-labelledby="memberModalLabel">
<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="memberModalLabel">Message from Administrators</h4>
</div>
<div class="modal-body">
// mesages will be inserted here
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
function loadlink(){
$('.modal-body').load('templates/sendMessage.php?userID=<?=$userInfo['uniqueid'];?>',function () {
// maybe add a condition to see if nothing is returned
// and not show it
$('#memberModal').modal('show');
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 10000);
</script>
I have a php script that loops over the results of a database query and prints them out. I am trying to load them into an Admin Interface Panel with AJAX, but to no avail. My job requires me to write mostly backend code, so I haven't gotten around to learning much JS/Jquery. Anyways, I have a page "insert.php" that has a button I want to click and have it call the results from the "posts.php" page. Here are my files
insert.php
Load Posts
</div>
</div>
<div class="row main">
<div class="small-8 columns" id="posts">
</div>
</div>
</div>
posts.php
<?php
require_once 'connect.php';
$user = 'admin';
$sql = "SELECT * FROM posts WHERE author = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $user);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$id = $row['id'];
$title = $row['title'];
$author = $row['author'];
$date = $row['date'];
$smalltext = $row['smalltext'];
$bodytext = $row['bodytext'];
$images = $row['images'];
$imagelist = split(' ', $images);
$shorttext = str_replace(
array("\r\n", "\n"),
array("</p><p>", "</p><p>"),
$smalltext);
echo
"
<div class='row main'>
<h1 class='padding-top-12 bottom-rule-green'>$title</h1>
<div class='small-2 columns'>
<p class='text-justify small-text'>
Post MetaData goes here
</p>
</div>
<div class='small-10 columns bottom-rule-red text-justify'>
<p>
$shorttext
";
foreach ($imagelist as $key => $value)
{
echo "<img src='users/$author/img/$value'>";
}
echo
"
</p>
</div>
</div>
<div class='row main small-text padding-top-1'>
<div class='small-2 small-oofset-2 columns'>
<a href='posts/$author/$id'>Edit Post</a>
</div>
<div class='small-4 columns'>
Timestamp: $date
</div>
<div class='small-4 columns'>
Author: <a href='users/$user'>$user</a>
</div>
</div>
";
}
?>
postAjax.js
$.ajaxSetup ({
cache: false
});
var loadUrl = "../../includes/posts.php";
$(function(){
$('#ajaxbtn').on('click', function(e){
e.preventDefault();
$('#ajaxbtn').fadeOut(300);
$.post(loadUrl, {language: "php", version: 5},
function(res){
$("posts").html(res)
}, "html");
});
});
This is the file that loads my scripts into the page
<!--Foundation Framework Necessities-->
<script type="text/javascript" src="../../assets/js/vendor/jquery.js"></script>
<script type="text/javascript" src="../../assets/js/foundation/foundation.min.js"></script>
<script type="text/javascript" src="../../assets/js/postAjax.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
When I click the #ajaxbtn button, it fades out so I know the JS is being called to that element onclick, but it doesn't post the results of posts.php. I think this may just be my misunderstanding of how Ajax works; if you would please tell me what I did wrong.
Try changing,
$("posts").html(res)
to
$("#posts").html(res)
Also I see some mistakes in your code in posts.php
You are not embedding php variables in strings properly.
I believe you need to use a delegated event. Change your code from:
$('#ajaxbtn').on('click', function(e)
to:
$('#ajaxbtn').on('click', 'a', function(e)
This way event handlers will fire as expected even if the contents of that parent element change. I had the same issue and this solved it. Good luck.
How to setup an div to auto refresh?
I use Transcript theme for wordpress, in single.php is on call for inner php page:
</div><!-- /innerLeft -->
<?php include (TEMPLATEPATH . '/innerNarrowSidebar.php'); ?>
<?php include (TEMPLATEPATH . '/innerWideSidebar.php'); ?>
<div class="clear"></div>
The code inside innerNarrowSidebar.php
<?php if($trns_options['enArc'] == 1) { ?>
<div class="widget">
<h3 class="widget_sTitle_b"><?php _e('Archives','Transcript'); ?></h3>
<ul>
<?php wp_get_archives('type=monthly'); ?>
</ul>
</div>
<?php } ?>
And than in innerpage_120x600.php
I have some google adsense
**NOTE**: I added this code in innerNarrowSidebar.php but dosn't work , the div dosn't autorefresh
There is the code that i have added:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 10000 ); ///////// 10 seconds
$(function() {
SANAjax = function(){
$('#narrowSidebar').fadeOut("slow").load('ads/innerpage_120x600.php').fadeIn("slow");
}
});
</script>
If this is not possible, how to make an text widget to auto refresh?
As described in comments:
<script language="JavaScript">
$j(function($) {
var SANAjax = function(){
//Add here anticache modificator:
var rnd=Math.random();
$('#narrowSidebar').fadeOut("slow").load('ads/innerpage_120x600.php?nc='+rnd).fadeIn("slow");
}
setInterval(SANAjax, 10000 ); ///////// 10 seconds
});
</script>