Modal reopens automatically after clicking the closing button - javascript

I've been trying to dynamically create a modal view in a table.
The data used to create the table is comming from a sql database.
Now my problem:
Whenever I click on a button called "Details" the modal view is opening and contains the data it should.
However, when I try to close the view with the "Close"- Button or the X in the top right corner the modal view will close for a second and reopen on its own.
The background will get darker after I do one of the above mentioned operations.
Here comes the tricky part. Whenever I close the view with the escape button on my keyboard, it'll close as it should and I'll get back to my previous view.
<?php
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)) {
$thisId = $row['id'];
$thisModalId = 'modal'.$thisId;
$thisModalIdHref = '#'.$thisModalId;
$thisFormDoneId = $row['id'].'FormDoneId';
// Create table row
echo "<tr onclick=\"input\" data-toggle=\"modal\" href='$thisModalIdHref'>";
echo "<td>";
echo $row['Name'];
echo "<td>";
echo $row['Betreff'];
echo "<td>";
echo "<button class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target='$thisModalIdHref'>";
echo "Details";
echo "</button>";
echo"<div class=\"modal fade\" id='$thisModalId' tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">";
echo "<div class=\"modal-dialog\">";
echo "<div class=\"modal-content\">";
echo "<div class=\"modal-header\">";
echo "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>";
echo "<h4 class=\"modal-title\" id=\"myModalLabel\">Weitere Information </h4>";
echo "</div>";
echo"<div class=\"modal-body\">";
echo "<dl class=\"dl-horizontal\">";
echo "<dt>Bereich</dt>";
echo "<dd>" .$row['Bereich']. "</dd>";
echo "</dl>";
echo"</div>";
echo"<div class=\"modal-footer\">";
echo "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>";
echo "<button type=\"button\" class=\"btn btn-primary\">Save changes</button>";
echo"</div>";
echo"</div>"; //<!-- /.modal-content -->
echo"</div>";//<!-- /.modal-dialog -->
echo"</div>";//<!-- /.modal -->
echo "</td>";
echo "</tr>";
}
?>
For clarification:
If the $thisModalId is changed to the previous "MyModal" it works, but the button will, as it's supposed to, open the same text.
If you need any more source code or something else, I'd be more than happy to post it.
Thanks in advance for your help guys.
Best regards.

This is probably caused by the fact that your modal div is defined inside the element (tr) that the onclick handler is defined on. If the close button handler does not consume the click event, it will bubble to the containing elements all the way up (div, div, div, div, td, tr). When it gets to the tr, the onclick handler will execute and the modal will open again.
Obviously, you can solve this by not having your modal div inside your table structure, which doesn't really have a function anyway. This means that you will have to perform more than one separate loop, because the divs have to be all the way outside the table. This does not have to mean that your code will get messy if you take the advice of some of the commenters above and separate your PHP from your HTML a little bit.
Try something like this:
<?php
// Collect data
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
$modals = array();
while($row = mysql_fetch_assoc($query)) {
$modals[] = array(
'id' => 'modal' . $row['id'],
'href' => '#modal' . $row['id'],
'FormDoneId' => $row['id'] . 'FormDoneId',
'Name' => $row['Name'],
'Betreff' => $row['Betreff'],
'Bereich' => $row['Bereich'],
);
}
?>
<table> <!-- Or something -->
<?php
foreach ($modals as $modal) {
// Create table rows
?>
<tr onclick="input" data-toggle="modal" href="<?php echo $modal['href'] ?>">
<td>
<?php echo $modal['Name'] ?>
<td>
<?php echo $modal['Betreff'] ?>
<td>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="<?php echo $modal['href'] ?>">
Details
</button>
</td>
</tr>
<?php
}
?>
</table>
<?php
foreach ($modals as $modal) {
// Create modal divs
?>
<div class="modal fade" id='<?php echo $modal['id'] ?>' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Weitere Information </h4>
</div>
<div class="modal-body">
<dl class="dl-horizontal">
<dt>Bereich</dt>
<dd><?php echo $modal['Bereich'] ?></dd>
</dl>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div> //<!-- /.modal-content -->
</div>//<!-- /.modal-dialog -->
</div>//<!-- /.modal -->
<?php
}

Related

Using isotope, why doesn't my grid update?

This is my first time ever using isotope. So, I create the isotope instance inside of my document.ready function like so:
var grid = $('.headshots-list');
grid.isotope({
// options
itemSelector: '.headshots-list-item-alt',
layoutMode: 'fitRows',
sortBy: '[data-number]'
});
Then I set the values of each element in my grid layout including setting the data-number attribute.
$("#headshot_" + $(this).val()).attr('data-number', 2); // Users who are not chairpersons
$("#headshot_" + $(this).val()).attr('data-number', 1); // Users who are chairpersons
Then I try to sort the grid. Currently, I am using the setTimeout only because I was testing to see if maybe I had a race condition but it made no difference. The grid does not order itself in the way that I am expecting so that the user with data-number 1 will show before all other users. These attributes are being set. I have viewed the elements in dev tools to be sure.
As I mentioned earlier, this is the first time I have ever used isotope so not sure what I am doing wrong. Any pointers in the right direction will be greatly appreciated.
As requested below, this is the HTML where I build out the li that goes with this.
<li id="headshot_<?php echo $user->ID; ?>"
data-number = "1" class="headshots-list-item-alt js-headshot <?php echo $user_terms_classes . ' ' . $board_status . ' ' . $number; ?>"
data-toggle="modal"
data-target="#memberInfo_<?php echo $member_id; ?>">
<div class="headshot-list-item-inner">
<div class="headshot-list-photo">
<?php //suppress photo until they come in
?>
<?php if ($photo_id): ?>
<?php // echo wp_get_attachment_image( $photo_id, 'Avatar' ); ?>
<?php else: ?>
<?php // echo '<img src="https:somedomain.com/imgs/user_img.jpg"/>'; ?>
<?php endif; ?>
</div>
<h4 class="no-margin">
<?php echo $name; ?>
<input type="hidden" class="user_id" value="<?php echo $user->ID; ?>">
<span style="font-size:14px; display: block; position: relative; width: 100%;"
class="chair_designation" id="chair_designation_<?php echo $user->ID ?>">
</span>
</h4>
<p class="no-margin"><?php echo $title; ?></p>
<span class="headshot-list-item-tag">View Bio</span>
</div>
</li>

How to use bootstrap dismissible alerts in html/php/JQuery and change $_SESSION array

I have notifications on an $_SESSION array:
f ex.
11=>'1234-Client A:Message is coming, Ok:0'
14=>'3456-Client B:Message is coming, Not Ok:3'
aso.
I loop through these to print it out in dismissible bootstrap alerts.
The last indicator in the message is deciding what alert to use.
When I close a notification I want to close it AND update the $_SESSION array with '...:9' to indicate that this is closed and will not show the next time the page is reloaded.
I pass the Id to the JQuery, since this can differ from record to record, but how can I use this on the same PHP-page to change the $_SESSION array for the correct record Id?
I am trying with this code:
invoices.php:
...
$id = $_POST["id"];
echo 'Id: ' . $id . '<br />';
...
<?php if(isset($_SESSION['UploadMessage'])) :
foreach($_SESSION['UploadMessage'] as $key => $val):
$pos = strrpos($val, ":");
$alert = substr($val, $pos+1);
$val = substr($val, 0, $pos);
echo $val . ' ' . $alert . '<br />'; //'\n'
$message = $val; ?>
<?php if($alert == 0) : ?>
<div class="alert alert-success alert-dismissible" id="<?=$key;?>" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true" id="<?=$key;?>">×</span></button>
<strong>Ok! </strong><?=$message?>
X
</div>
<?php endif; ?>
<?php if($alert == 1) : ?>
<div class="alert alert-info alert-dismissible" id="<?=$key;?>" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true" id="<?=$key;?>">×</span></button>
<strong>Info! </strong><?=$message?>
</div>
<?php endif; ?>
<?php if($alert == 2) : ?>
<div class="alert alert-warning alert-dismissible" id="<?=$key;?>" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true" id="<?=$key;?>">×</span></button>
<strong>Warning! </strong><?=$message?>
</div>
<?php endif; ?>
<?php if($alert == 3) : ?>
<div class="alert alert-danger alert-dismissible" id="<?=$key;?>" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true" id="<?=$key;?>">×</span></button>
<strong>Åtgärda! </strong><?=$message?>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
...
<!-- JavaScript -->
<script>
$('button.close').on('click', function (obj) {
var id = obj.target.id;
console.log("Close "+id);
$.post('invoices.php', { 'id': 'id'});
});
</script>
I know that PHP has already loaded the document when the foreach-loop
is running, but how can I pass the value of the array-Id when I click the
close button on each notification and change the array value for this?
Can anyone help a newbie out?
I have tried changing the javascript into this, but it doesn't work.
I get the correct id in the alert box, but no update of $_SESSION is made when I reload the page.
// $.post('invoices_ajax.php', { 'id': 'id'});
$.ajax({
type: "POST",
url: 'invoices_ajax.php',
data: ({id:id}),
success: function(data) {
alert(data);
}
});
});
In my Ajax file I have this code:
<?php
$id=$_POST['id'];
echo $id;
if(isset($_SESSION['UploadMessage'])) {
foreach($_SESSION['UploadMessage'] as $k => &$v) {
echo $k . ' ' . $v . '<br />';
if($k == $id) {
$pos = strrpos($v, ":");
$v = substr($v, 0, $pos).':9';
echo $v . '<br />';
}
}
}
?>

Edit specific record that inside php looped

at the moment i've coded out like
<div class="row">
<div class="col-lg-12">
<table id="usertable" class="table table-bordered table-hover text-center">
<thead>
<th class="col-lg-1 text-center">User ID</th>
<th class="col-lg-4 text-center">Username</th>
<th class="col-lg-4 text-center">Password</th>
<th class="col-lg-2 text-center">Role</th>
</thead>
<tbody>
<?php
require('dbconnectmssql.php');
$sql = "select [User_ID],[user_decoded],[pass_decoded],[permission] from [rfttest].[dbo].[users]";
$query = sqlsrv_query ($conn , $sql);
if($query === false)
{die( print_r( sqlsrv_errors(), true));}
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_NUMERIC))
{
echo "<tr>";
foreach($row as $x => $a)
{
echo "<td>".$a."</td>";
}
echo "<td>";
echo "<a href='#' ><span class='glyphicon glyphicon-wrench' aria-hidden='true'></span></a>";
echo "<a href='usercontrol.php?del=$row[0]'>";
echo "<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>";
echo "</a>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
/table>
</div>
</div>
it's all about query out and show how many user in the table.
I've done the delete-record by link to PHP file and $_GET data (maybe improve later if have another solution that you will suggest )
Another things that i want to do is
Edit specific record without redirected to another page
My idea for right now is hidden form that popup after click edit such as i've click then form pop up with data record that stored and user can edit it and save it by submit to PHP file and then redirect back to this page
something like : Contain form within a bootstrap popover? post
the popover link
<div id="popover-head" class="hide">
some title
</div>
<div id="popover-content" class="hide">
<!-- MyForm -->
</div>
but i still can't figured out
How can i code out to make the link to open the specific popover-head/content maybe popover-head/content must be contain in id or something ?
What about PHP
What about JS/JQ also
Any solution what i just want only something to edit specific record that echo out
Sorry for my bad English
Thanks
You likely want to use AJAX for this.
This looks so painful to me - and if it worked a google spidering would delete all users on the page:
}
echo "<td>";
echo "<a href='#' ><span class='glyphicon glyphicon-wrench' aria-hidden='true'></span></a>";
echo "<a href='usercontrol.php?del=$row[0]'>";
echo "<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>";
echo "</a>";
echo "</td>";
echo "</tr>";
}
It could be written
} ?>
<td>
<a href='#' ><span class='glyphicon glyphicon-wrench' aria-hidden='true'></span></a>
<a class="del" href='#' data-userid='<?PHP echo row["User_ID"]; ?>'>
<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>
</a>
</td>
</tr>
<?PHP } ?>
And then
$(function() {
$(".del").on("click",function(e) {
e.preventDefault(); stop the page from reloading
var id=$(this).data("userid");
$.get("usercontrol.php?del="+id,function() {
alert(id + "deleted");
});
});
});
To edit
Popup a form with the data using .show() and .hide()
change the data
AJAX the changes on submit - be sure to use preventDefault to
stop actual submission $("form").on("submit",function(e) { e.preventDefault(); $.post("save.php",$(this).serialize(),function(data) { alert("saved"); $("#formDiv").hide() });});
show the result
close the popup

Dynamic content in Bootstrap Modal

I have little problem with Bootstrap modal. I embedded HTML code in PHP. For some reasons I want couple of modals in page.
<?php
//Looping modals...
for($i = 0; $i < 5; $i++){
echo '<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">';
echo 'Launch demo modal';
echo '</button>';
echo '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">';
echo '<div class="modal-dialog" role="document">';
echo '<div class="modal-content">';
echo '<div class="modal-header">';
echo '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>';
echo '<h4 class="modal-title" id="myModalLabel">';
echo $i; //Title goes here.
echo '</h4>';
echo '</div>';
echo '<div class="modal-body">';
echo '...'; //Content goes here.
echo ' </div>';
echo '<div class="modal-footer">';
echo '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
echo '<button type="button" class="btn btn-primary">Save changes</button>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
Loop works fine but I can't update title and content I my modal. All content and title data stays the same.
I tried this:
$(document).ready(function(){
$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
});
Well...I'm not sure how to use this correctly.
I mean I don't know hot to use jQuery in PHP code. I tried saving jQuery code in script.js file and including in my modal:
echo '<script type = "text/javascript">';
include ('script.js');
echo '</script>';
Anyway, that doesn't work.
So, how to change modal content dynamically?
You need to change the modal ID every time you loop - so add the $i var in the modal ID for example. You must have unique IDs in HTML or jQuery / Bootstrap modal won't find the correct modal.
Change
echo '<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal'.$i.'">';
and
echo '<div class="modal fade" id="myModal'.$i.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">';
Alternately, you might rather try varying modal content based on a trigger button.
Also - just a style note: You can have multi-line echo statements, which might make your code a little easier to read. Or close the PHP tage and re-open when done with HTML:
echo '
<div ... >
<div ... >
</div>
</div>
';
or (instead of echo):
<?php
for ($i ... ) {
?>
<div ... >
<div ... >
</div>
</div>
<?php
} //ending for loop
?>

Set hidden field value by Javascript

How can I pass USER_ID of the tag < a > for a Javascript function Javascript that set a hidden field?
I tried the Javascript function showConfirm(), but the hidden field isn't being filled. It stays null... I think the onClick attribute, of the field deleteid, is wrote wrong.
I want fill this field by javascript. How can I?
The message of error says
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1
probably because the hidden field "id_action" isn't receiving datas of the function.
Whatever, the main problem is set the function showConfirm by paramters 'show', $row['id'] for the hidden field id_action.
<script>
function showConfirm (action, delID) {
if (action == 'show') {
document.confirm.id_action.value = delID;
}
}
</script>
<tbody>
<?php
if (!empty($_POST)) {
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
}
$listUser = new User;
$result = $listUser->listarUsers();
if (is_array($result)) {
foreach ($result as $row) {
echo "
<tr>
<td align='right'>" . $row['id'] . "</td>
<td>". $row['name'] . " ".$row['sobrename']."</td>
<td>" . $row['email'] . "</td>
<td>" . $row['login'] . "</td>
<td>
<a data-toggle='modal' id='deleteid' data-target='#modal_delUser' onclick=\"showConfirm('show'," . $row['id'] . ")\">
Remove
</a>
</td>
</tr>";
}
}
unset($listUser);
?>
</tbody>
<!-- Button trigger modal -->
<div class='modal fade' id='modal_delUser' tabindex='-1' role='dialog' aria-labelledby='modal_delUserLabel' aria-hidden='true'>
<div class='modal-dialog'>
<div class='modal-content panel-danger'>
<div class='modal-header panel-heading'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='modal_delUserLabel'>The user will be deleted</h4>
</div>
<div class='modal-body'>
Are you sure continue?
</div>
<div class="modal-footer">
<form role="form" id="confirm" action="users.php" method="post">
<input type="hidden" name="id_action">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="submit" class="btn btn-danger">Yes</button>
</form>
</div>
</div>
</div>
</div>
Here the SQL that I am generating from the query
public function deletarUsuario($id) {
$del_id = $this->db->real_escape_string(trim($id));
if ($update = $this->db->query("DELETE FROM usuario WHERE id = $del_id")) {
if ($this->db->affected_rows) {
echo "<div><p>Deleted user!</p></div>";
}
else {
echo "<div><p>Failed to delete user.</p></div>";
}
}
else {
echo "<div><p>". $this->db->error."</p></div>";
echo "<script>$('#modal_erroBD').modal('show');</script>";
}
}
Do it in php by using $id_action = $_POST["id_action"]
Check if you are passing the id at this stage:
change
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
to
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
echo $del_id;
}

Categories

Resources