Opening a Modal Window "using" PHP - php

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

Related

How to use Wordpress contant form 7 and fancy box to display particular section when on_sent_ok or fancybox close

I have a problem with wp contact form 7 and fancy box. I need to show a hidden content after the form is submitted. When my form is submitted i couldn't able to display that code.
<div class="col-md-offset-8 col-md-4 text-center"><a class="btn btn-primary show" data-fancybox="modal" data-src="#modal" href="javascript:;">View The Technical Specification </a></div>
//Fancybox Modal
<section>
<div id="modal" style="display: none; padding: 50px 5vw; max-width: 800px;text-align: center;">
<h3>Provide the details</h3>
<?php echo do_shortcode('[contact-form-7 id="816" title="Download From"]'); ?>
</div>
</section>
once this form is submitted i want to display something like this
<div id="show" >
....................
.............
.......................
</div>
Here is the Script i tried
$('.fancybox').fancybox({
afterClose: function () {
$('#show').fadeIn(); // or .show()
})
});
i couldn't display the particular section..
Looks like you did not use correct selector and therefore your custom options were not applied. It should be like this:
$('[data-fancybox="modal"]').fancybox({
afterClose: function () {
$('#show').show()
}
});
Demo - https://codepen.io/anon/pen/YrYqzy
When we submit the contact form 7 it will redirect from url http://demo.com/ to http://demo.com/#wpc7-fm.Here if fancybox form #modal is active then the url will change http://demo.com/#modal. Once the form submitted the url will replace to http://demo.com/#wpc7-fm in that case our fancybox will disappears due to the url #modal replaced with #wpc7.`
Example:-
$('[data-fancybox="modal"]').fancybox({
afterClose: function () {
$('#show').show()
}
});
Above code just trigger $('#show').show()
But after form submission above code will become inactive in the case.
jQuery(document).ready(function() {
if ( location.hash != 0 && location.hash == '#wpcf7-fm' ){
$('#show').show();
}
});
This Location hash can activate the hidden content.

Load MySQL data dynamically by unique id into Bootstrap modal -CodeIgniter

Having successfully eliminated the issue from a previous question I posed in add limit to data passed to bootstrap modal with foreach() in codeigniter, I now find myself with the residue of that issue. As succinctly posited by #webcrazymaniac;
The idea is to have a unique modal window, with it's unique id for each article, uniquely called with the corresponding button
According to the solution listed in Send parameter to Bootstrap modal window?, I should be able to have my desired effect as stated above - adapted as;
On page Modal
<!-- alert view -->
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='#myModal<?php echo $a->art_id;?>'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
</div>
</div>
jQuery Script
<script type="text/javascript">
$( document ).ready(function() {
$('#myModal').on('show.bs.modal', function (e) { //Modal Event
var id = $(e.relatedTarget).data('id'); //Fetch id from modal trigger button
$.ajax({
type : 'POST',
url : 'query.php', //Here you will fetch records
data : 'post_id='+ id, //Pass $id
success : function(data){
$('.form-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Modal Trigger Button
echo "<a href='#myModal/".$a->art_id."' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
query.php
<?php
//Include database connection here
$dsn = 'mysql:host=localhost;dbname=articles;charset=utf8';
$user ='';
$pass ='';
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES, false);
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
if($_POST['art_id']) {
$id = $_POST['art_id'];
$category = $_POST['cat_name'];
$public_date = $_POST['public_date'];
$description = $_POST['description'];
// Run the Query
$sql = "SELECT `art_id`, `cat_name`, `public_date`, `description` FROM `articles` WHERE `art_id`='?'";
$stmt = $pdo->prepare($sql);
// Fetch Records
$stmt->execute();
}
?>
It all works to call the modal, but this attempt only nets me the 5th result on-page for all (green) buttons clicked. As (maybe) an important note, I'm having trouble with data-id='#myModal<?php echo $a->art_id;?> fitting into the modal trigger button as it destroys the popup of the modal. I know I have to maybe pull a destruction mode in order to change to another ID like so;
$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
Now, mind you, I'm not especially conversant in jQuery, so what I've come up with is based on a solid few hours of reading and experimentation. Having pored over numerous examples, I'm still at a loss as to exactly how to make this all work. I'm really stuck as I'm getting the same result (off by a factor of either the display of the first or fifth result for clicking green buttons) whether I'm trying this straight PHP or jQuery. It seems like every question that I've read in this category of question gets me to the current dilemma I'm in where if I use the PHP version solution, I'm returned the 1st page result for every view button on the page. jQuery solution returns the fifth page result for each view button. This is strange indeed... Not even changing out the jQuery for simplified js like this;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
($ 'a[data-toggle=modal]').click ->
target = ($ #).attr('data-target')
url = ($ #).attr('href')
($ target).load(url)
I was pulling for that snippet to rescue me, but, no. Neither did this one;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function(){
$('#myModal').on('shown.bs.modal', function () {
var $modal = $(this),
modal_title = $(this).data('modal-title'),
modal_params = $(this).data('modal-params');
if(typeof modal_title !== typeof undefined && modal_title !== false) {
title = modal_title;
}
else{
title = 'Title';
}
$.ajax({
cache: false,
type: 'POST',
url: 'query.php',
data: modal_params,
success: function(data) {
$modal.find('.modal-title').html(title);
$modal.find('.modal-body').html(data);
}
});
});
});
</script>
//crabbed from
//https://stackoverflow.com/questions/35702374/bootstrap-modal-with-individual-attributes
But, as par for the course, no love... There's either Human Error to blame, or I'm just missing something plainly hiding in full view. Having read more than 200-plus questions today, I'm having problems re-reading this for formatting, etc. (lol!). Learned tons, but still stuck.
UPDATE
In the time since I've looked at what #progrAmmar suggested, I went back to try and refine my approach. The key issue is how to make the jQuery reload process;
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
clear out the modal so that upon click of another button, the corresponding table row content flows in like water. I'm having problems figuring out what sequencing is correct for the jQuery - as it stands now;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function() {
// Fill modal with content from link href
$('.myModal').on('click', function(e) {
var link = $(this).data('href');
$('#myModal').modal('show');
$('#myModal .modal-body').load(link );
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
})
</script>
Which results in the view below:
If you look on the bottom-left of the image you'll see the corresponding id value is 3, but the open modal is pulling content from id value 5. I'm still having the process of calling the modal and displaying table row go smoothly, but the modal reload process is bent. Suggestions? I'm out of ideas at this point.
#progrAmmar, I went back to your proffered suggestion, but these are the following things preventing me from fully adapting;
article/index (controller/index function)
public function index()
{
$modal = $this->article_model->modal($art_id=NULL);
$category = $this->category_model->listAll();
$article =$this->article_model->index($this->limit);
$total_rows=$this->article_model->count();
$config['total_rows']=$total_rows;
$config['per_page']=$this->limit;
$config['uri_segment']=3;
$config['base_url']=site_url('article/index');
$this->pagination->initialize($config);
$page_link =$this->pagination->create_links();
$this->load->view('admin/article',compact('article', 'page_link', 'category', 'modal'));
}
article_model.php
public function modal($art_id)
{
$data = array();
$this->db->select('art_id', 'cat_name', 'public_date', 'description');
$this->db->from('tbl_article');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
Still trying to figure out where the needle is here. Thanks again for your suggestions #progrAmmar.
UPDATE ANNOYANCES
Back to purely PHP as jQuery wasn't doing anything different for me - even after playing around with #progrAmmar's code. Now I'm left back at ground zero and having read for another two hours (mainly # the jQuery forum). :sigh:
ALMOST THERE....
After consulting the BS 3.3.5 docs, I know my answer is in the Varying modal content based on trigger button section. Tried to extrapolate this;
//Modal window trigger button
echo "<a href='".base_url()."article/$a->art_id' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
//jQuery code
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var id = button.data('id') // Extract info from data-* attributes
var href = button.data('href') // Extract info from data-* attributes
var target = button.data('target') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('Title:')
modal.find('.modal-body').val('Category:')
modal.find('.modal-body').val('Date:')
modal.find('.modal-body').val('Content:')
$('#myModal > div.modal-body).empty();
})
I'm pretty sure I'm doing it wrong as I just can't get my head around any attempted extrapolations - been poring over other solution examples on SO, but am still working out approaches to the above coding. Research in motion...
Extrapolating Code Proffered By #progrAmmar;
Controller Article(.php)
------------------------
public function index()
{
$data['modal'] = $this->article_model->modal($art_id); // Gets all the data
$this->load->view('('admin/article',compact('article', 'page_link', 'category', 'modal') $data);
}
View article(.php)
------------------
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='myModal'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
<input type="hidden" id="hidId" value="<?php echo $a->art_id;?>" />
</div>
</div>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
//Finally call the html via JavaScript
$.get(window.base_url + 'index.php/article/'+ id, function (data) {
$('#myModal' > div.modal-body).empty();
$('#myModal').html('data');
$('#myModal').modal('show');
}
Did a little juggling to fit in this attempt, but there's no change as the fifth page result is never bumped out by another content ID as shown below;
Still stuck in the same position before...round and round we go ミ●﹏☉ミ
Of the section I'm interested in within the docs;
$('#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
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
my primary issue is;
HOW do I extrapolate Update the modal's content?
THIS is essentially the core of my impedance and not located by an intensive search of the BS docs. If I could sync up some kind of way to force-reload the content within the modal, I have my answer. In fact the closest I've found to any example of how to (maybe) approach this was a post here (sorry forgot which one) detailing how to reload an image within a modal by targeting the src element;
//And then you just change the src attribute of the picture element from your function.
var picture = button.data('picture')
$('#picture').attr('src',picture);
THAT'S IT!* (theoretically)...Between the above example and the Varying modal content based on trigger button example, I'm on my way to losing it. I can't believe I can't just make the logical connection required to fire off the force-reload. I just don't see it, and every example I've used thus far keeps me in the same place.
Having gone through fifty-plus JQuery code examples, not one of them did squat as far as activating any functionality, so I'm off attempting to use it as any sort of solution. NONE of the answers under this topic worked (even a little). This is the 1st time in my career where I've been completely stumped with nowhere to turn.
Here are the things I've tried:
Situation 1
Initially dealing with an HTML table <table class="table table-condensed"> listing out the articles db elements of 'art_id', 'title', 'cat_name', 'public_date', 'image', the table elements are scooped from the db with foreach ($article->result() as $a){.
The table ends with the activity buttons, the 1st of which is the BS modal trigger (unable to change table being echoed out in PHP - just mucks it all up);
echo "<a href='".base_url()."article/#myModal/$a->art_id' button class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
Situation 2
The modal data-toggle (as posted above) is the trigger for the modal to popup and is located on page bottom;
<!-- alert view -->
<div id="myModal<?php echo $a->art_id" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<?php
$i=0;
foreach ($article->result() as $a){
?>
<div id="#myModal<?php echo $a->art_id ?>" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<?php
if(!$i=0) break;
$i++;
}
?>
</div>
If the modal foreach isn't both included and augmented like so;
<?php
if(!$i=0) {
break;
} else {
$i++;
}}
?>
then the modal pulls all of the $a->art_id elements into view simultaneously like so;
And, even with the necessary jQuery at the bottom (after the modal);
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(document).ready(function($) {
$('.myModal').click(function(event){
var $link = $(this);
new BootstrapDialog({
title : 'Title : ' + $link.attr('href'),
content : $('<div>Loading...</div>').load($link.attr('href')),
buttons : [{
label : 'Close',
onclick : function(dialog){
dialog.close();
}
}, {
label : 'View',
cssClass: 'btn-primary',
onclick : function(dialog){
alert('The content of the dialog is: ' + dialog.getBody().html());
dialog.close();
}
}]
}).open();
event.preventDefault();
});
});
});
</script>
//crabbed from - https://stackoverflow.com/questions/14045515/how-can-i-reuse-one-bootstrap-modal-div/14059187#14059187
Situation 3
NOTHING WORKS.... The jQuery is not destroying and reloading the modal, so I'm only getting that 1st on-page result from the 1st button on the page (completely correct content and ID). The most frustrating thing is if I hover over each button, the correct content ID is returned. I think it's safe to say that it's not any problem with the code - I have to investigate WHY that specific code isn't working on-page. Confusing because I'm using jQuery already;
<script src="<?php echo base_url(); ?>asset/js/jquery.js"></script>
<script src="<?php echo base_url(); ?>asset/js/jquery-latest.min.js"></script>
putting these two lines just above the modal and jQuery at the bottom of the page. It looks as if there is a conflict somewhere preventing the jQuery-driven script from firing. The only conflict I can maybe even see is that with the CKEditor that loads just above the jQuery.
Even with switching to another code block;
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.myModal').click(function(){
$(this).find('.inner').clone().appendTo('#myModal .modal-content');
$('#myModal .modal-title .modal-body .control-group.hide').show();
$('#myModal').modal();
});
$('#myModal').on('hidden', function(){
$('#myModal .inner').remove();
});
});
</script>//forgotten SO crabbing
I keep getting the same results. Since throwing in the towel, I've come upon several SO solutions which suggest the scenario I want, but I can never physically fulfill them and it making me angrier than a rattlesnake in a Texans' boot. Not only were these questions completely similar to mine, but they (almost) all got upvoted # +1 or better, and the selected solutions did nothing to extract me from my bottleneck.
This is an issue that I'd like to see cleared up as I know there's a solution, and from the numerous Fiddles and Plunkers, they're all similar in nature with slight variations that I haven't been able to employ.
The simplest (and probably the easiest) way to call a MODAL for data is to call the HTML from the server.
Create a separate view for your model.
Call the data into it, load the model from the controller.
Here's how I am calling my Modal with codeigniter
Controller
public function EditData($id)
{
$data['entity'] = $this->Home_model->getData($id); // Gets all the data
$this->load->view('Home/modal_data', $data);
}
views/Home/modal_data.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit <?= $entity['name'] ?></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<label>Name</label>
<input type="text" id="txtName" class="form-control" value="<?= $entity['name'] ?>" />
<input type="hidden" id="hidId" value="<?= $entity['id'] ?>" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success has-spinner" id="btnSave">
<span class="spinner"><i class="glyphicon glyphicon-spin glyphicon-refresh"></i></span>Save
</button>
</div>
Make sure you have a modal div on your page to call the html into.
views/Home/index.php
<html>
.
.
.
<body>
<div id="home_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content" id="home_modal_cont">
</div>
</div>
</div>
</body
</html>
Finally call the html via JavaScript
$.get(window.base_url + 'index.php/home/EditData/'+ id, function (data) {
$('#home_modal_cont').empty();
$('#home_modal_cont').html(data);
$('#home_modal').modal('show');
}

Hide a div in while user session exists

I have this problem: I can't find out how to hide a div that appears just when session begins. So I a have a X button for closing, and when the page is refreshed, the div appears again! But I don't want to stop the session.
My code:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
And js
<script>
$(document).ready(
function() {
$(".got-points-close").click(function() {
$(".got-points-bg").hide("fast");
});
});
</script>
If it is on refresh then it is easy; just do it in the PHP session; like this:
HTML:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer']) && empty($_SESSION['first_load'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
and in your PHP before then (like on login/session start) - this will obviously need significant editing since you haven't included your PHP I can't guess it very well, but this should provide a starting point:
<?php
//load user check pseudo code
if !empty($_SESSION[user]) and whatever other checks... {
$_SESSION['first_load'] = False; //important line number 2
}
//login pseudo code to demonstrate placement within your code
if user & pass = valid {
$_SESSION['first_load'] = True; //important line number one
}
That is assuming you want th div output but not displayed on subsequent loads.
Interesting question, how about something like this?
<?php
if(isset($_SESSION['variable'])){
sleep(3); /* Duration(in seconds) div is displayed for */
echo
"<script>
$( document ).ready(function() {
$(".got-points-bg").hide("fast");
});
</script>";
}
?>
try this
<?php error_reporting(0); session_start(); if(empty($_SESSION['user'])) echo "<div id='togglediv'> My text here </div>"; ?>
hope it will work

jQuery code will not work/apply to elements that are within a file called from an ajax using javascript

Hoping someone can point me in the right direction to an annoying problem.
To summarize before I put the code; I have two files.. a html file with javascript called "bookings.php", and a php file with php "getBookings.php".
The bookings.php file contains all the static information like menus, text etc along with javascript + ajax calls.
I'm calling the getBookings file successfully with javascript/ajax and works well and i don't have any problems with it.
My problem is, that from the file that is loaded (getBookings.php); there are some html elements that i need to toggle. The jQuery for it, I have included in the bookings.php file.. but the jquery won't apply or work when the ajax file is called.
All the contents on getBookings.php gets loaded into an #bookingSummary element.
Now, my code is very long, so i will include all the important parts..
// Usual Head Content, Meta, CSS, jQuery files
// Filters
<script language="javascript" type="text/javascript">
function bookings()
{
var fltr="";
if(document.frm.bkid.value != "")
fltr+='bkid='+document.frm.bkid.value+'&';
if(document.frm.customer.value != "")
fltr+='cid='+document.frm.customer.value+'&';
if(document.frm.site.selectedIndex != 0)
fltr+='sid='+document.frm.site.value+'&';
if(document.frm.status.selectedIndex != 0)
fltr+='st='+document.frm.status.value+'&';
if(document.frm.supp.selectedIndex != 0)
fltr+='sup='+document.frm.supp.value+'&';
if(document.frm.datefrm.value != "")
fltr+='dfrm='+encodeURI(document.frm.datefrm.value)+'&dto='+encodeURI(document.frm.dateto.value);
document.getElementById('bookingsummary').innerHTML="<br /><p align='center'> <img src='img/bigloading.gif'></p>";
url='get/getBookings.php?'+fltr;
getAjaxRec(url, viewbookings);
}
function viewbookings()
{
if (xmlHttp.readyState == 4 && (xmlHttp.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById("bookingsummary").innerHTML = xmlHttp.responseText;
}
}
</script>
The Above code is the javascript that all works fine.. the following is the html code that calls the above function - bookings():
<!-- Several Form fields are here..-->
<input type="button" value="Apply Filter" class="searchBtn" onClick="bookings();">
<!-- Show booking results -->
<div id="bookingsummary"></div>
Now, within the getBookings file there is an html element with a class name "hiddenDetails" that i need to toggle and the Jquery for it is:
<script type="text/javascript">
$(document).ready(function() {
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium");
});
});
</script>
The above code all works apart from the jquery.. here is a snippet from the getBookings.php file.. the part i want to apply the jquery to..
<?php
// A while loop happens then..
$result="
<div class=\"bookingKeyInfo\">
<div class=\"lb1\"><input type=\"checkbox\" name=sup1x".$rw['id']." ></div>
<div class=\"lb2\">".$rw['id']." </div>
<div class=\"lb3\">".date('d/m/Y', strtotime($rw['pickupDate']))." <strong><font color=\"#FF0000\">".date('H:i', strtotime($rw['pickupTime']))."</font></strong></div>
<div class=\"clearLeft\"></div>
</div>
<div class=\"bookingKeyDetails\">
<div class=\"b-one\"><img style=\"margin-top:9px; padding-bottom: 5px;\" src=\"$base_dir/img/".strtolower($rw['status']).".png\"></div>
<div class=\"b-two\"><img id=\"isCustomerEmailed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-three\"><img id=\"isSupplierEmailed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-four\"><img id=\"isSupplierConfirmed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-trip\">".substr($rw['DA'],0,6)."..<strong> to </strong> ".substr($rw['DB'],0,6)."..</div>
<div class=\"b-pax\">".$rw['pax']." Pax</div>
<div class=\"b-cost\">€$cost </div>
<div class=\"b-supplier\">".substr($sup,0,10)."..</div>
<div class=\"clearLeft\"></div>
<div class=\"hiddenDetails\">More Booking Information...</div>
</div>";
echo $result;
?>
I know this is a very long description of the problem.. so I have tried to give my code exactly as it is..
Could anyone shed some light, as to why the jQuery isn't working.. cz it works separately, just not on any element that is called from getBookings..
The problem is, you're binding an event handler with jQuery to bookingKeyDetails before it actually exists on the page. Remember that this element is being added to your html only after the page is loaded, so any actions you make in $(document).ready(function() { will not apply to it.
Bind the event handler only after you change the html:
function viewbookings()
{
if (xmlHttp.readyState == 4 && (xmlHttp.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById("bookingsummary").innerHTML = xmlHttp.responseText;
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium');
});
}
};
Since the HTML element you need to toggle was never on the page when the calling page instantaiate the jQuery to toggle, you need to reinitialize the function after a successful call from your ajax.
You can use jQuery .success callback function for their AJAX call tools... I use that to help with this kind of processing instead of native AJAX. Makes life simpler and better cross browser support.
Just call your toggle function after the success.
http://api.jquery.com/jQuery.post/
It's very obvious that it will not toggle because you have writtent the Jquery in the "bookings.php". During the page load of bookings.php, it will not find any content of the getBookings.php so that Jquery will not apply as no element is available with that id.
You have to bind the event for the toogle on Ajax success event of the when you are calling for getBooking.php.
$.ajax({
url: URL,
success: function(){
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium");
});
},
error: function(){
alert('failure');
}
});
You're using single and double quotes in your function call
$(this).next('.hiddenDetails').slideToggle('medium");
user 'medium' or "medium"

Opening a link inside a div in the same div

I am trying to make a div where I include PHP web pages into it, however when I click any link inside the div, it loads in new window.
Does anyone know how to solve this problem?
I also tried using an iframe instead of a div but it caused other problems.
HTML code:
<div id="cover5">
<div id="warning">
<?php include 'SignIn.php'; ?>
<p align="center">
Home
</p>
</div>
</div>
JS code:
function cover5() {
var cover = document.getElementById('cover5');
if (vis) {
vis = 0;
cover.style.display='block';
}
else {
vis = 1;
cover.style.display='none';
}
}
You have to make a distinction bitween the client-side and the server-side of a Web application.
<?php include 'SignIn.php'; ?> is a server-side command, because of the <?php ?>, which means that the user will never see that line exactly.
If your SignIn.php file contains for example my link, the user will only get the ouput of that inclusion, i.e.
<div id="warning">
<a href="go-there.php">my link</a
</div>
When the user clicks on the link, his browser will load it as if this <a /> would have been hard written within your HTML code directly, and then open it in a new window.
I don't no how to do it using native JS, but with jQuery, you can try something like this:
$(function() {
$("#warning a").each(function() {
$("#warning").load($(this).attr("href"));
});
});
To render html from a specific link within an element on the page you need to run an ajax GET call, and load the html. Then insert the response in your div.
using jQuery:
$("a").click(function(){ //calls function when anchor is clicked
var link = $(this).prop("src"); //finds the link from the anchor
$.get(link,function(data, status, xhr){ //makes an ajax call to the page
$("#myDiv").html(data); //replaces the html of #myDiv with the returned page
});
});
Hope that helps
HTML CODE :
<div id="cover5">
<div id="links">
<p align="center">
Home
</p>
</div>
<div id="warning">
<?php include 'SignIn.php'; ?>
</div>
</div>
and JS code:
function cover5() {
var cover = document.getElementById('warning');
if (vis) {
vis = 0;
cover.style.display='block';
}
else {
vis = 1;
cover.style.display='none';
}
}
Whenever an user click on the link in "links" div it will call JS function "cover5()"
You can use jQuery or ajax to pop-up "warning" div
In your code you added the links to the worning div so as when in second time ti will hide all the links form there.

Categories