Jump to content

Modal Population Only Correct First Time


Adamhumbug

Recommended Posts

I have a user table that is being used to show all of the users in the system.  To edit a user you click the manage button at the end of a line -> this pops a modal.

On that model there is the option to delete the user -> this pops a confirmation modal.

This all works great.

The issue comes when you get to the confirmation page and back out.

If you then select another user and try and delete them, the information on the confirmation modal is that of the first user you went to delete.

Find code below

<?php if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user_id'])){
		header("location: index.php");
		exit;
}

$_SESSION['this_page'] = 'users';
include '_includes/head.php'; ?>
<div class="container-fluid">
	<div class="row">
		<?php include '_includes/header.php'; ?>
	</div>
	<div class="row">
		<div class="col-sm-2 p-0 bg-dark text-light" style="height: calc(100vh - 50px);">
			<?php include '_includes/nav.php'; ?>
		</div>
		<div class="col-sm-10">
			<?php
				if(isset($_SESSION['updateUser'])){
					$eqn = $_SESSION['user'];
					echo '<div id="infomessage" class="alert alert-'.$_SESSION["actionstatus"].' mt-3 text-center text-uppercase">';
							echo $eqn . " " . $_SESSION['updateUser'];
					echo "</div>";
				}
				unset($_SESSION['updateUser']);
				unset($_SESSION['user']);
			?>
			<div class="userList">
				<?php
				include '_includes/dbconn.php';
				$stmt = $conn->prepare("
				                       	SELECT user_id, user_email, user_firstname, user_lastname, user_mobile, user_role_id, role_name, user_account_level_id, user_level_name, 
				                       	GROUP_CONCAT(job_eventname SEPARATOR ', ') as eventname 
				                       	from ssm_user left join ssm_role on role_id = user_role_id 
				                       	left join ssm_user_level on user_account_level_id = user_level_id 
				                       	left join ssm_job on job_manager_id = user_id 
				                       	Group by user_id
										");
				$stmt->execute();
				$stmt->bind_result( $uid, $ue, $ufn, $uln, $um, $urid, $urole, $ualid, $ulname, $ename);
					echo "<table class='table table-striped table-hover table-bordered text-center mt-3'><thead class='thead-dark'><tr>
					<th>User ID</th>
					<th>Full Name</th>
					<th>Email Address</th>
					<th>User Role</th>
					<th>System User Level</th>";

					if($_SESSION['user_level']=='100'){
							echo "<th>Admin</th>";
						}

					echo "</thead></tr>
					<tbody>";

				while($stmt->fetch()){
					echo "<tr>
					<td class='align-middle'>" . $uid . "</td>
					<td class='align-middle'>" . $ufn . ' '. $uln . "</td>
					<td class='align-middle'>" . $ue . "</td>
					<td class='align-middle'>" . $urole."</td>
					<td class='align-middle'>" . $ulname . "</td>";

					if($_SESSION['user_level']=='100'){
					echo <<<TEXT
					<td><a class="btn btn-primary col-sm-12" data-toggle="modal" data-userid="$uid" href="#userModal" data-firstname="$ufn" data-lastname="$uln" data-email="$ue" data-accountlevel="$ualid" data-mobile="$um" data-role="$urid" data-activesheets="$ename">Manage</a></td>
TEXT;
					}
				}
					echo "</tr>
					</tbody></table>";
				
				?>
			</div>
<!-- User Modal -->
<div class="modal fade" id="userModal">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" id="userModalLabel">Users</h4>
				<button type="button" class="close" data-dismiss="modal" >
				<span >&times;</span>
				</button>
			</div>
			<form method="POST" id="updateUserSubmit">
				<div class="modal-body">
					
					<ul class="nav nav-tabs mb-3 ml-3 mr-3">
						<li class="nav-item"><a class="nav-link active" href="#tab1" data-toggle="tab">User Info</a></li>
						<li class="nav-item"><a class="nav-link" href="#tab2" data-toggle="tab">Password</a></li>
					</ul>
					<div class="tab-content">
						<div class="tab-pane active" id="tab1">
							<input type="hidden" name="UM-uid" id="UM-uid">
							<div class="md-form">
								<div class="col-md-12 mb-3">
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">First Name</span>
										</div>
										<input name="UM-firstName" id="UM-firstName" type="text" class="form-control" placeholder="First Name" required>
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">Last Name</span>
										</div>
										<input name="UM-lastName" id="UM-lastName" type="text" class="form-control" placeholder="Last Name" required>
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">Mobile Number</span>
										</div>
										<input name="UM-mobileNumber" id="UM-mobileNumber" type="text" class="form-control" placeholder="Mobile Number" required>
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">Email Address</span>
										</div>
										<input name="UM-emailAddress" id="UM-emailAddress" type="text" class="form-control" placeholder="Email Address" required>
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">Role</span>
										</div>
										<select name="UM-roleId" id="UM-roleId" class="custom-select">
											<?php
											
											$sql = "SELECT role_id, role_name FROM ssm_role ORDER BY role_name ASC";
											if($result = mysqli_query($conn, $sql)){
												if (mysqli_num_rows($result)>0){
													while ($row = mysqli_fetch_array($result)){
														echo "<option value='{$row['role_id']}'>{$row['role_name']}</option>";
													}
												}
											}
											?>
											
										</select>
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">User Level</span>
										</div>
										<select name="UM-accountLevelId" id="UM-accountLevelId" class="custom-select">
											<?php
											echo "<option value ='0'>Please Select</option>";
											$sql = "SELECT user_level_id, user_level_name, user_level_value From ssm_user_level ORDER BY user_level_name ASC";
											if($result = mysqli_query($conn, $sql)){
												if (mysqli_num_rows($result)>0){
													while ($row = mysqli_fetch_array($result)){
														echo "<option value='{$row['user_level_id']}'>{$row['user_level_name']}</option>";
													}
												}
											}
											?>
											
										</select>
									</div>
									
								</div>
							</div>
						</div>
						<div class="tab-pane" id="tab2">
							<div class="md-form">
								<div class="col-md-12 mb-3">
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">New Password</span>
										</div>
										<input name="UM-pass" id="UM-pass" type="text" class="form-control" placeholder="New Password">
									</div>
									<div class="input-group mb-3">
										<div class="input-group-prepend">
											<span class="input-group-text modalprew">Confirm Password</span>
										</div>
										<input name="UM-pass-conf" id="UM-pass-conf" type="text" class="form-control" placeholder="Confirm Password">
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button id="updateUser" formaction="actions/update-user-action.php" type="submit" class="btn btn-success">Update User</button>
					<a data-toggle="modal" data-userid="" data-activesheets="" href='#userDeleteConfirmationModal' id="callDeleteUserConf" class="btn btn-danger">Delete User</a>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- End Of User Modal -->


<!-- Start of modal -->
<div class="modal fade" id="userDeleteConfirmationModal" tabindex="-1" role="dialog">
	<div class="modal-dialog" >
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" id="deleteUserConfLabel">Delete - </h4>
				<button type="button" class="close" data-dismiss="modal" >
				<span >&times;</span>
				</button>
			</div>
			<form method="POST" id="deleteUserConfForm">
				<?php
					$uid = $_SESSION['user_id'];
					$stmt = $conn->prepare("SELECT user_firstname, user_lastname FROM ssm_user WHERE user_id = ?");
					$stmt -> bind_param('i', $uid);
					$stmt -> execute();
					$stmt -> store_result();
					$stmt -> bind_result($fname, $lname);
					$stmt -> fetch();
				?>
				<div class="modal-body">
					<div class="md-form">
						<div class="col-md-12 mb-3">
							<p id="active-sheets-label"></p>
							<p id="active-sheets"></p>
							<p>This action cannot be reversed</p>
							<div class="form-group">
								<label id="reqConfVal" for="confirmationWithName"><?php echo $fname." ".$lname ?></label>
								<input type="text" class="form-control" id="confirmationWithName" placeholder="Enter Name">
								<input name="staffMemberId" type="hidden" value="" id="staffMemberId">
								<small id="conconfirmationWithNameHelp" class="form-text text-muted">Enter your full name as shown above to delete the user.</small>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button class="btn btn-default">Cancel</button>
					<button name="delete-user-button" formaction="actions/delete-user-action.php" id="deleteUserButton" type="submit" class="btn btn-danger">Delete User</button>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- end of modal -->
		
		<div class="col-sm-12"><?php include '_includes/footer.php'; ?></div>
	</div>
</div>

</div>


		<script>
			///////////////////////
			//popuate user modal //
			///////////////////////
		$('#userModal').on('show.bs.modal', function(event) {
		// Button that triggered the modal
		var button = $(event.relatedTarget)
		//data elements
		var userid = button.data('userid')
		var firstname = button.data('firstname')
		var lastname = button.data('lastname')
		var email = button.data('email')
		var level = button.data('accountlevel')
		var mobile = button.data('mobile')
		var role = button.data('role')
		var modal = $(this)
		modal.find('.modal-title').text('Update User')
		modal.find('.modal-body #UM-uid').val(userid)
		modal.find('.modal-body #UM-firstname').val(firstname)
		modal.find('.modal-body #UM-lastname').val(lastname)
		modal.find('.modal-body #UM-emailAddress').val(email)
		modal.find('.modal-body #UM-accountLevelId').val(level)
		modal.find('.modal-body #UM-mobileNumber').val(mobile)
		modal.find('.modal-body #UM-roleId').val(role)
		/////////////////////////////////////////////////////////////
		//pass info from modal to modal putting data on the button //
		/////////////////////////////////////////////////////////////
		var x = modal.find('#callDeleteUserConf');
		x[0].dataset.userid = button.data('userid')
		x[0].dataset.activesheets=button.data('activesheets')
		x[0].dataset.firstname=button.data('firstname')
		x[0].dataset.lastname=button.data('lastname')

		})

		////////////////////////////////
		//populate confirmation modal //
		////////////////////////////////
	
		$('#userDeleteConfirmationModal').on('show.bs.modal', function(event) {
		// Button that triggered the modal
		var button = $(event.relatedTarget)
		//data elements
		var userid = button.data('userid')
		var firstname = button.data('firstname')
		var lastname = button.data('lastname')
		var activesheets = button.data('activesheets').split(", ").join("<br/>")
		console.log(activesheets);
		var modal = $(this)
		modal.find('#deleteUserConfLabel').text(firstname + ' ' + lastname)
		modal.find('#active-sheets-label').text('This user has the following active sheets')
		modal.find('#active-sheets').html(activesheets)
		modal.find('#staffMemberId').val(userid)


		})

	/////////////////////////////////
	//set sidebar active indicator //
	/////////////////////////////////
	if(document.getElementById('user')){
		document.getElementById('user').classList.add('show')
	}
	if(document.getElementById('userList')){
		document.getElementById('userList').classList.add('blOrange')
	}
	$('#infomessage').fadeIn('fast').delay(3000).fadeOut('3000');



///////////////////
//stacking modal //
///////////////////
  $(document).ready(function () {

    $('#openBtn').click(function () {
        $('#myModal').modal({
            show: true
        })
    });

        $(document).on('show.bs.modal', '.modal', function (event) {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function() {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });


});
</script>

1241048330_Screenshot2020-01-13at14_08_39.thumb.png.295e12feb1cd8d6e1195509d6dcfa5ba.png

1329173350_Screenshot2020-01-13at14_08_46.thumb.png.2939a0925edb6af7ecf4b54fd1b430ed.png756662627_Screenshot2020-01-13at14_08_59.png.e8979e36158b4aca7bedfefe9247eb53.png

 

 

 

Edited by Adamhumbug
Link to comment
Share on other sites

6 minutes ago, ginerjm said:

Way too much spaghetti code to wade thru.....

Let's start here:  How are you "saving" this info that is coming up incorrect?  Obviously that is the problem.  Old data is being kept and re-used when you don't want it to.

Its the js that is at the end of the code.

 

var x = modal.find('#callDeleteUserConf');
		x[0].dataset.userid = button.data('userid')
		x[0].dataset.activesheets=button.data('activesheets')
		x[0].dataset.firstname=button.data('firstname')
		x[0].dataset.lastname=button.data('lastname')

		})

pulling it from the button on the first modal and putting it on the delete button to be passed onto the second modal.

I expected that it would update every time the modal was popped

Link to comment
Share on other sites

ok so the JS that is doing all of the work here is as follows:

 


			///////////////////////
			//popuate user modal //
			///////////////////////
		$('#userModal').on('show.bs.modal', function(event) {
		// Button that triggered the modal
		var button = $(event.relatedTarget)
		//data elements
		var userid = button.data('userid')
		var firstname = button.data('firstname')
		var lastname = button.data('lastname')
		var email = button.data('email')
		var level = button.data('accountlevel')
		var mobile = button.data('mobile')
		var role = button.data('role')
		var modal = $(this)
		modal.find('.modal-title').text('Update User')
		modal.find('.modal-body #UM-uid').val(userid)
		modal.find('.modal-body #UM-firstname').val(firstname)
		modal.find('.modal-body #UM-lastname').val(lastname)
		modal.find('.modal-body #UM-emailAddress').val(email)
		modal.find('.modal-body #UM-accountLevelId').val(level)
		modal.find('.modal-body #UM-mobileNumber').val(mobile)
		modal.find('.modal-body #UM-roleId').val(role)
		/////////////////////////////////////////////////////////////
		//pass info from modal to modal putting data on the button //
		/////////////////////////////////////////////////////////////
		var x = modal.find('#callDeleteUserConf');
		x[0].dataset.userid = button.data('userid')
		x[0].dataset.activesheets=button.data('activesheets')
		x[0].dataset.firstname=button.data('firstname')
		x[0].dataset.lastname=button.data('lastname')

		})

		////////////////////////////////
		//populate confirmation modal //
		////////////////////////////////
	
		$('#userDeleteConfirmationModal').on('show.bs.modal', function(event) {
		// Button that triggered the modal
		var button = $(event.relatedTarget)
		//data elements
		var userid = button.data('userid')
		var firstname = button.data('firstname')
		var lastname = button.data('lastname')
		var activesheets = button.data('activesheets').split(", ").join("<br/>")
		console.log(activesheets);
		var modal = $(this)
		modal.find('#deleteUserConfLabel').text(firstname + ' ' + lastname)
		modal.find('#active-sheets-label').text('This user has the following active sheets')
		modal.find('#active-sheets').html(activesheets)
		modal.find('#staffMemberId').val(userid)


		})


///////////////////
//stacking modal //
///////////////////
  $(document).ready(function () {

    $('#openBtn').click(function () {
        $('#myModal').modal({
            show: true
        })
    });

        $(document).on('show.bs.modal', '.modal', function (event) {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function() {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });

I am not sure why the data on the confirmation modal is only populated once and not every time it is laoded

 

Edited by Adamhumbug
Link to comment
Share on other sites

I haven't waded through all the code but I wondered, from the symptoms, if the cause is similar to this situation.

Consider this simple html script

<!DOCTYPE html>
<html>
<head>
<title>Sample Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
    $().ready( function () {
        
        $("button").click( function() {
            $("#main").append("<button>Click to add new button</button><br>")
        })
    })
</script>
</head>
<body>
<header>
    <h1>Sample</h1>
</header>
<div id="main">
     <button>Click to add new button</button> 
     <button>Click to add new button</button> 
     <button>Click to add new button</button>
     <br><br>
</div>
</body>
</html>

Very simple -  buttons which, when clicked, add another button for you to click.

  • You click a button and, lo, another appears.
  • Click a new button - nothing!
  • Click an original button and another appears.

The on-click event handler was created just after the form loaded and so was only applied to button objects that existed then. New buttons are not assigned the handler.

I was wondering if a similar thing is affected your script. You only get values from the stage the form loaded

Link to comment
Share on other sites

40 minutes ago, Barand said:

I haven't waded through all the code but I wondered, from the symptoms, if the cause is similar to this situation.

Consider this simple html script


<!DOCTYPE html>
<html>
<head>
<title>Sample Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
    $().ready( function () {
        
        $("button").click( function() {
            $("#main").append("<button>Click to add new button</button><br>")
        })
    })
</script>
</head>
<body>
<header>
    <h1>Sample</h1>
</header>
<div id="main">
     <button>Click to add new button</button> 
     <button>Click to add new button</button> 
     <button>Click to add new button</button>
     <br><br>
</div>
</body>
</html>

Very simple -  buttons which, when clicked, add another button for you to click.

  • You click a button and, lo, another appears.
  • Click a new button - nothing!
  • Click an original button and another appears.

The on-click event handler was created just after the form loaded and so was only applied to button objects that existed then. New buttons are not assigned the handler.

I was wondering if a similar thing is affected your script. You only get values from the stage the form loaded

It would appear that that is correct.

However, when the first modal launches, everything is being updated, it is only when the second launches that IT is not being updated.

The button to launch the second modal has the following html

<a data-toggle="modal" data-userid="10" data-activesheets="" href="#userDeleteConfirmationModal" id="callDeleteUserConf" class="btn btn-danger" data-firstname="Sally" data-lastname="Lawrence">Delete User</a>

showing me that it is being updated and updates every time i pick a new user.

First time around i can see the second modal being populated in inspector and can also see it not changing the second time it runs.

 

 

Link to comment
Share on other sites

i have just put some console logs in.

i put the first at the end of the section with the comments "pass info from modal to modal putting data on the button"

and the second at the end of the section with the comments "populate confirmation modal".

The second one works fine first time but never changes after it has been used once.  Keeps dumping the same value. 

I dont know if this is helpful

Link to comment
Share on other sites

The confirmation modal has had its code updated

$('#userDeleteConfirmationModal').on('show.bs.modal', function(event) {
		// Button that triggered the modal
		var button2 = $(event.relatedTarget)
		console.log(button2.data('userid'))
		console.log(event.relatedTarget)
		//data elements
		var userid = button2.data('userid')
		var firstname = button2.data('firstname')
		var lastname = button2.data('lastname')
		var activesheets = button2.data('activesheets').split(", ").join("<br/>")
		var modal = $(this)
		modal.find('#deleteUserConfLabel').text(firstname + ' ' + lastname)
		modal.find('#active-sheets-label').text('This user has the following active sheets')
		modal.find('#active-sheets').html(activesheets)
		modal.find('#staffMemberId').val(userid)
};

Note the console logs:

The first

console.log(button2.data('userid'))

gives me 8

and the second

console.log(event.relatedTarget)

gives me

<a data-toggle="modal" data-userid="10" data-activesheets="" href="#userDeleteConfirmationModal" id="callDeleteUserConf" class="btn btn-danger" data-firstname="Sally" data-lastname="Lawrence">Delete User</a>

which is very confusing as they are looking at the same thing

Link to comment
Share on other sites

6 minutes ago, Barand said:

Puzzling indeed.

Does locating the element that does have data-userid=8 help to clarify what's going on?

BTW, I think the closing line of your event handler is missing the final ")"

The data-userid=8 is from the first go around when everything works as expected and doesnt seem to shed any light on it.

Ahh, i caught and corrected that.  Thanks

Edited by Adamhumbug
Link to comment
Share on other sites

1 hour ago, Adamhumbug said:

Note the console logs:

The first


console.log(button2.data('userid'))

gives me 8

and the second


console.log(event.relatedTarget)

gives me


<a data-toggle="modal" data-userid="10" data-activesheets="" href="#userDeleteConfirmationModal" id="callDeleteUserConf" class="btn btn-danger" data-firstname="Sally" data-lastname="Lawrence">Delete User</a>

which is very confusing as they are looking at the same thing

And if you console.log(button2) as well?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.