I'm trying to show a bootstrap modal after submitting a form and getting the result from the database. The page has to reload and show the extra modal so that the user can try to log in again.
I've tried to reload the page and then echo the script
Here is what I have for now
<? php
if(condition)
echo "<script>$('#modal').modal('show')</script>";
?>
...
<div class="modal fade" id="modal" tabindex="-1" role="dialog"</div>
The page is either reloading without the modal, or a blank page. I expect it to load with the added modal.
Have you tried tying the modal to a JS method, then calling the method from PHP?
<?php
if($condition)
echo "<script>showModal()</script>";
?>
function showModal() {
$('#modal').modal('show');
}
Edit:
You could try something like this:
<script>
$(function(){
if (<?php echo $condition ?> === true) {
$('#modal').modal('show');
}
});
</script>
Related
I'm using Bootstrap modal popup window,this is the button and url
Apply Now
<div class="modal fade" id="applynowModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
// Modal popup contents
<div class="modal-body">
// contents <?php echo $_GET['id']; // I need to get data-id value here.... ?>
</div>
</div>
I need to pass a unique id when Apply now button is clicked, and get the value in modal-body, How can I do this?
Using jquery, it can be easy.
$( '.but_apply' ).click( function() {
var id = $( this ).attr( 'data-id' );
$( '#applynowModal' ).find( '.modal-body' ).html( id );
});
Please note that PHP is a server side script and attaining the "when clicked" event happens on the client side.
Unless you really want the id to be passed only on clicked, you can just passed it as it is.
But then, I'll assume that you really want it to happen only on click. Then you can use a javascript (or bootstrap's jQuery)
$('#applynowModal').on('shown.bs.modal', function () {
// PUT THE LOGIC HERE OF PASSING THAT ID USING $(this).attr("data-id")
})
In my code I'm returning a array of items/designs which im previewing using HTML as you can see in the following screenshot:
Once I'm clicking on a item/design a form modal will popup and offer the user some selects and input fields.
The code looks like the following:
<?php foreach($designs as $design): ?>
<!-- HTML code to display designs which are returned from a PHP class -->
<?php endforeach; ?>
<div id="modal_form_vertical" class="modal fade">
<!-- Modal HTML code -->
</div>
As you can see I'm storing the modal code outside the foreach loop.
Since I'm able to click different items/designs I'm not sure how to use the urls/names/ids which are returned by the index position of the array.
Question: How would I use the PHP variables which are aviable inside the foreach loop inside the modal? Do I really have to create a modal foreach design/items by placing the modal code inside the foreach loop?
What you need is to add the variable to the modal trigger button as data attribute against which you can fetch or retrieve the relative information from database via modalevent listener & ajax method
Modal trigger buttorn
<?php foreach($designs as $design): ?>
<button data-toggle="modal" data-target="#modal_form_vertical" data-designid="<?php echo $variableId;?>" class="btn btn-default">Modal</button>
<?php endforeach; ?>
Modal event listener & Ajax method
$(document).ready(function(){
$('#modal_form_vertical').on('show.bs.modal', function (e) {
var designid = $(e.relatedTarget).data('designid'); //get the id
alert(designid);
var dataString = 'designid=' + designid;
$.ajax({
type: "POST",
url: "includes/design_content.php",
data: dataString,
cache: false,
success: function(data){
$("#designcontent").html(data);
}
});
});
});
Create design_content.php
<?php
//Include DatabaseConnection
//$_POST['designid'];
//Run query
//Fetch Data
//Echo data to show in Modal
?>
Modal HTML
<div id="modal_form_vertical" class="modal fade">
<!-- Modal HTML code -->
<div id="designcontent"></div> //Here will show the data fetched via ajax.
</div>
How I can show a specific modal depending on a variable in php which is modified in the url.
I'm using as responsive framework Bootstrap.
I have a page containing several modals, each corresponding to a product. I need to make a link from other parts of the site to go to page "products.php" and automatically display the required product.
E.g:
href="products.php?prod=1"
So far, I have only succeed in showing the modal when loading the page, but if I add or change the variable, it has no effect, not working at all.
This is what I have:
At the beginning
<?php
//Variable to choose which modal to show, default = 1
$prod = 1;
?>
Then the modal which has an id for identification.
<div class="modal fade" id="product1" tabindex="-1" role="dialog" aria-hidden="true">
<!-- Content of the modal -->
</div>
Then the script that show the modal when the page loads.
<script type="text/javascript">
$(document).ready(function(){
<?php if ($prod == 1) {
echo "$(document).ready(function () {var a = 'PD1'; alert(a); });";
echo "$('#product1').modal('show');";
}elseif ($prod == 2) {
echo "$(document).ready(function () {var a = 'PD2'; alert(a); });";
echo "$('#product2').modal('show');";
};
?>
});
</script>
Any idea?
You not gathering the value of the product variable from the URI. To accomplish this at the top of the page where you have $prod=1; you can put the following line of code :
$prod = (isset($_GET['prod']))?$_GET['prod']:"1";
This tells the system to get the value of the prod= in your url if it can't find it then use "1" as a default.
This is not the ideal answer, there are quite a few reasons not to access $_GET/$_POST variables in this way without proper filtering. I leave that for you to research.
You are doing opposite, should be
<?php if ($prod == "1") { ?>
<script type="text/javascript">
$(document).ready(function(){
var a = 'PD1';
alert(a);
$('#product1').modal('show');
});
</script>
<?php } elseif ($prod == "2") { ?>
<script type="text/javascript">
$(document).ready(function(){
var a = 'PD2';
alert(a);
$('#product2').modal('show');
});
</script>
<?php } ?>
I am trying to load the comments of a particular post on a modal. For this I need to pass the post id to the modal and then fetch the corresponding comments.
The modal is triggered by the following:
<a class="xyz" data-toggle="modal" data-target="#compose-modal" data-id="<?php echo $list[$i]->getID(); ?>">View Comments</a>
And the modal is defined at the bottom of the page as follows:
<div class="modal fade" id="compose-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- here i need to use php to fetch the comments using post id -->
</div>
</div>
</div>
PHP is executed before the page is returned to the browser. Once you see the page in your browser, all the PHP has already been executed. What you probably want to do is use AJAX. Here is a general outline of how you would do it:
Have a PHP page that takes the ID and returns the data you want as a JSON.
api.php
$theId = $_POST['theId'];
//Get the information you want, and turn it into an array called $data
header('Content-Type: application/json');
echo json_encode($data);
In your html, you should trigger the modal using an onclick attached to the "View Comments":
<a class="xyz" onclick = "launch_comment_modal(<?php echo $list[$i]->getID(); ?>)">View Comments</a>
then,at the bottom with your other javascript:
<script>
$('#compose-modal').modal({ show: false});
function launch_comment_modal(id){
$.ajax({
type: "POST",
url: "api.php",
data: {theId:id},
success: function(data){
//"data" contains a json with your info in it, representing the array you created in PHP. Use $(".modal-content").html() or something like that to put the content into the modal dynamically using jquery.
$('#compose-modal').modal("show");// this triggers your modal to display
},
});
}
</script>
Just pass the content via ajax with a php page
and echo the content in the modal
I have just made an Esiest way to pass php dynamic data to Bootstrap modal in Laravel > 5
currently i am using larvel 7.
This is HTML DOM using onclick event, simplly call the JavaScript function
<li>Some Option</li>
& pass Dynamic Variable.
This is JavaScript Code
<script type="text/javascript">
function showModal(id=0){
$('#collectionModal').modal('show');
// here is the id of that element where do you want to display / have the passed value
// in my case i am taking in a hidden input which id is = bookID , i am using a form in my modal that why
$('#bookID').val(id);
}
</script>
This is modal's HTML where i am getting the passed value like:
<input type="hidden" name="book_id" id="bookID" value="">
and finally i am submiting the form in modal using javaScript & Ajax.
I am creating a log in system in PHP and I'm trying to make it a little nicer.
When you log out, you get redirected back to index.php. Like this:
header("loaction: index.php?logout=true")
This makes the url look like www.mysite.com/index.php?logout=true. I then use the following code:
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
$notification = "You've been logged out!";
}
to get the value of logout from the URL and do something with it.
I have a small popout window that will display the notification variable's value. In this case it's "You've been logged out!" My question is how do I get the modal window to display when the page loads and when the url equals /index.php?logout=true ?
All comments, answers, and suggestions are greatly appreciated!
Thanks!
- Ryan
First of all,
You can't "Open a Modal Window using PHP" directly.
You can only do this only by exchanging variables (via JSON or XML), or embedding PHP conditions right into your markup.
PHP and JavaScript are independent.
My question is how do I get the modal window to display when the page
loads and when the url equals /index.php?logout=true ?
There are two ways you can achieve this.
First: Make a good use of embedding PHP conditions right into the markup.
Second: Have somewhere hidden input, like (<input type="hidden" id="showModal" />) and then check if it exists via JavaScript itself.
For example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function(){
if ( document.getElementById('showModal') ){
alert('Box'); //replace with your own handler
}
}
</script>
</head>
<body>
<?php if ( isset($_GET['logout']) && $_GET['logout'] === 'true' ): ?>
<input type="hidden" id="showModal" />
<?php endif;?>
</body>
</html>
Are you looking for something like:
<script>
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
echo 'alert("You\'ve been logged out!");'
}
?>
</script>
EDIT: I believe you are looking for something like this for a modal window (using jQuery)
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
$message = "You've been logged out!";
?>
<script>
$(function() {
$("#dialog").dialog();//if you want you can have a timeout to hide the window after x seconds
});
</script>
<div id="dialog" title="Basic dialog">
<p><?php echo $message;?></p>
</div>
<?php } ?>
I know it is an old post, but to help someone in future with similar quest, I guess the following may help to get into right directions ( I have tested the below code myself, so please make adjustment).
<?php if(isset($_GET['logout']) && $_GET['logout'] === 'true'){
$message = "You've been logged out!";
?>
<script>
$(function() {
$('#myModal').modal('show');
});
</script>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"><?php $message ?></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php } ?>
Ok, so your existing code is like this snippet, and the problem you're having is that you want to show a jQuery/Bootstrap modal triggered by/with PHP, but jQuery/JS hasn't loaded yet (so you'll get a "$ undefined" error).
When you say "a small popout window" I'm assuming you mean a bootstrap type modal.
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
$notification = "You've been logged out!";
}
}
What I did was move the PHP code block to the end of the .php file, after jQuery (etc), and have an include, so it would look like this (assuming the name of your modal is id="logoutModal"):
logout.php
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
include("logout-modal.php");
}
}
logout-modal.php
<?php ?>
<script>
$('#logoutModal').modal('show');
</script>
<?php ?>
Not 100% sure this answers your question, but this works for me. Hope this helps.
Best way to get done this by using the PRG pattern.
index.php
1. Create the element for modal content in HTML
<div id=modal></div>
2. Style your #modal element
#modal {
position: fixed;
display: none; /*important*/
color: white;
text-align: center;
z-index: 1000;
width: 100%;
height: 80px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: crimson;
line-height: 2;
}
3. Define function how to show and disappear the modal box using jQuery
'use strict'
window.jQuery ?
$.fn.notify = function(interval) {
let el = $(this),
text = el.text(),
modal =()=> { // this will fire after the interval has expired
el.fadeOut(),
clearInterval(timer)
},
timer = setInterval(modal,interval)
!text.match(/\S+/) || el.text('') // this will fire when modal box contains text
.append(`<h3>${text}</h3>`)
.show()
}
: alert('jQuery required.')
4. Attach .notify() to the jQuery selector
$(()=>{
$('#modal').notify(1500) // 1500 is the interval in milliseconds
})
5. Insert the notification sent from PHP inside the #modal element
<div id=modal>
<?=
#$_SESSION["notify"]; // if this variable is not set, nothing will happen
unset($_SESSION["notify"]);
?>
</div>
6. Perform a simple $_GET request
<a href=parse.php?logout>Logout</a>
parse.php
7. Return a value using PHP in a $_SESSION variable
if (isset($_GET["logout"])) {
$_SESSION["notify"] = "You have been logged out.";
header("Location: index.php");
}
This is good practice. Once the logout request is sent to PHP, it will redirect to the index page with the result in a session variable. The PRG pattern does not always require a POST request. This example sends a GET request which is ok for logouts. Note that you have to place session_start(); at the top of your files.
Or you could even write the script inside if statement:
<?php
if(isset($_GET['logout']) && $_GET['logout'] === 'true'){ ?>
<script type="text/javascript>
window.open(yourhtml);
</script>
</php }
else {
// may be some other script
}
?>
Please download a Modal JS Library http://simplemodal.plasm.it
and Use the Condition
if(isset($_GET['logout'])) {
$logoutvalue = $_GET['logout'];
if($logoutvalue = "true") {
code to open the Modal as in the JS library.....
}