I want to make a popup appear in php - php

I am making a forum-like website in php and I added a button inside each question container to delete questions on the forum. I am looking for a way to make a popup appear when the user clicks the delete button. I am using bootstrap and I found a popup modal on the bootstrap website. With my current code, the popup appears when the button is clicked and it asks the user to confirm that he wants to delete his question. The problem is that I don't know how to get the ID of the question the users wants to delete so after I can delete it in my MySQL database.
This is my current button and it is inside a php echo '...'
<div class="col-1" title="delete your comment"><button name="delmsgbtn" class="btn-reseter" type="button" data-bs-toggle="modal" data-bs-target="#delmsg">delete</button></div>
And this is the popup modal from bootstrap that shows up when button is clicked
<div class="modal fade" id="delmsg" tabindex="-1" aria-labelledby="delmsgLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delmsgLabel">Are you sure you want to delete this message?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">cancel</button>
<button type="button" class="btn btn-danger">delete</button>
</div>
</div>
</div>
</div>
I had the idea to redirect the user to the same page but with the url containing the question id, so after I can have it using the get method. So I modified the button by adding a redirection.
New button also inside a php echo that is why the backslash
<div class="col-1" title="delete your comment"><button name="delmsgbtn" class="btn-reseter" onclick="location.href = \'course.php?courseid='.$_GET["courseid"].'&quesid='.$idQues.'\';" type="button" data-bs-toggle="modal" data-bs-target="#delmsg">delete</button></div>
But when doing this, the page refreshes and the popup disappears. Can you help me.

First, modify your modal open button. Should be something like this
<button class="btn-reseter delmsgbtn" data-comment_id="<?= PHP_COMMENT_ID ?>">delete</button>
Be sure to replace PHP_COMMENT_ID with an actual PHP variable that holds the comments ID.
Replace the "delete" button in the modal with a form.
<form method="POST" action="PHP_PROCESS_SCRIPT">
<input type="hidden" name="comment_id" id="comment_id_input"/>
<button type="submit" class="btn btn-danger">delete</button>
</form>
Make sure that PHP_PROCESS_SCRIPT points to the PHP script to process the comment deletion. Also, if applicable, make sure in this script that the user who is deleting the comment is actually allowed to.
Create a click handler to open the modal, instead of inline attributes.
<script>
$('.delmsgbtn').on('click', function() {
//update #comment_id_input in the popup form,
//based on data-comment_id added to the button from the first snippet
$('#comment_id_input').val($(this).data('comment_id'));
$('#delmsg').modal('show'); //open the modal
});
<script>
When the form is submitted, the PHP script you hooked up will get a value $_POST['comment_id'].
Alternatively, you could make an ajax call from a click handler attached to the delete button inside the modal. This is better if you want to prevent a page refresh. First, modify the delete button like this
<button id="delmsg_submit" type="button" class="btn btn-danger">delete</button>
Then, add some click handlers
<script>
var active_comment_id = null;
$('.delmsgbtn').on('click', function() {
//update active_comment_id,
//based on data-comment_id added to the button from the first snippet
active_comment_id = $(this).data('comment_id');
$('#delmsg').modal('show'); //open the modal
});
$('#delmsg_submit').on('click', function() {
if(active_comment_id) {
//send ajax call
}
});
<script>

I would put the id of the element with php
like
<button id="element-id-<?php echo $id ?>" class="myBtn" >
then i would use a javascript function to do execute the call on database
<script>
const btn = document.querySelector('.myBtn')
btn.addEventLIstener('click', () => {
const elementId = this.id //then remove the 'element-id-' from the value
const data = { id: elementId }
fetch( URLforBackend, {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify(data)
})
</script>
this will give to your backend the id.
in php, in there, just do the deletion

Related

Bootstrap Modal how to load PHP variable

I would like a simple form to be loaded in a bootsrap modal. Here is a link that loads a page with php variables but I would like modal to be shown.
Aktualizacja
How to edit modal get the php variable that is above? Here is the modal first line, but how should I make it to open the modal not a page?
<div class="modal fade" id="?????" tabindex="-1" role="dialog" aria-labelledby="?????"
aria-hidden="true">
Ia another modal that is working but it serves as add data form in a place of "?????" I have specific id. SO please feel free to replace "?????" with sth that is needed. Thank You.
I had the same problem and fixed it with some jQuery.
This is a link for deleting:
echo "<td><a rel='$comment_id' href='javascript:void(0)' class='delete_link'>DELETE</a></td>";
classic Bootstrap Modal:
<!-- Modal -->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Modal</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this ?</p>
</div>
<div class="modal-footer">
Delete
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
And some jQuery:
$(document).ready(function () {
$(".delete_link").on('click', function () {
var id = $(this).attr("rel");
var delete_url = "comments.php?delete="+ id +" ";
$(".modal_delete").attr("href", delete_url);
$("#myModal").modal('show');
})
})
So I used jQuery to open modal when clicked on the link and to take 'rel' attribute from it so I can use it later in modal, then targeted the specific delete button in modal and passed the url.
In short:
in the tag which represents to 'Edit' store a unique value like client id which represents the client
on clicking this element trigger an $(ajax).post() to get the that clients details
on ajax success use the response data to assign values to the modal form for editing
use modal('show') to display the modal with the populated form
on modal form submit, make sure that you have passed the client id with the form data for record updation in database
Store client id with the tag which represents the action
<span onclick="edit_client(<?php echo $klient->id;?>)" class="badge badge-primary">Edit</span>
On clicking this element call a function passing the client id ( You could also assign the client id to a data attribute and onclick function take the client id from it )
<script>
function edit_client(client_id = '' ) {
if(client_id!='') {
// call ajax. pass client_id as data
$(ajax).post({
'url': '', // url to get the client details
'data': {
client_id: client_id,
}
// other necessary properties
})
.done( function(data) {
// check for data status
// assign values to form elements accordingly to the structure of response data
$('#edit_modal #client_name').val($data['client_name']);
// like so for other elements also ( remember about the response data structure while assigning values to form elements)
$('#edit_modal').modal('show'); // show the edit modal which now has the client details
});
}
}
</script>

Ajax called page with button not triggering modal window with form variable

I have this following Ajax call which is trying to get some data in certain intervals
$(document).ready(function() {
x();
function x() {
var FD = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "qaVtagAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return false;
}
setInterval(x, 5000);
});
$("#assignQaOa").click(function() {
// trigger modal
});
Content of the Ajax call page qaVtagAjax.php as below
echo '<form method="post"> <div class="card" style="position: relative; border-color: black; !important ">
<div class="card-body">
<div class="row">
<input type="text" name= "srNum" id="srNum" value = "someValue" hidden>
<div class="col-sm"><button class="btn-primary modalButton" type="submit" name = "assignQaOa" id = "assignQaOa" title="Click to assign to some operator">Assign</button></div>
</div>
</div>
</div>
</form>
<br>';
As you can see there is a button in the form called assignQaOa. I want to trigger a modal window by clicking this button as show earlier
$("#assignQaOa").click(function() {
//trigger modal by doing Eg: $('#myModal').modal('show');
alert("Modal window showing");
});
As a first step, I tried to alert some message. But nothing is happening when I click the button. Does anyone have some idea why this way?
NB: Actual qaVtagAjax.php file has more html and php contents. Those are working correctly. So I simplified that codes for understanding the problem.
Edit 1
Following is the modal codes that I am using from bootstrap
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" id="tagSerial" name="tagSerial" hidden>
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Also I edited the button click code as below based on the suggestion. This time if I gave a simple alert, it is working. But modal is not showing
$(document).on("click", "#assignQaOa", function() {
//Alert is working. Eg: alert("some message");
$('#exampleModalCenter').modal('show'); //This is not working
});
Edit 2
Some post suggested the possibility that two time bootstrap.js was typed in the document. But for my case, it is not the case too. I only typed it once and I am using as below
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Does anyone know why this happening? As I mentioned in comments, if I removed the class fade from modal, then modal will show for a split second with this $('#exampleModalCenter').modal('show'); code
Edit 3
By doing e.preventDefault(), I am able to stop the form submission and show modal successfully. But now I have an element in the modal window that supposed to get some $_POST values from form submission. How can I get that $_POST value in the modal at this situation? My Javascript code as below
$(document).on("click", "#assignQaOa", function(e) {
$('#exampleModalCenter').modal('show');
$('#tagSerial').val($("#srNum").val());
e.preventDefault();
});
The following is the element in the modal window
<input type="text" id="tagSerial">
After many trial and errors, I found issue was due to I am using type = submit for the button. When I changed type = button, modal triggered and showed correctly. But I am still puzzled why when I used type = submit and removed the class fade, modal showing for a split second. Probably there is a work around to show it correctly too. I hope some expert from stack overflow can find out and tell me the problem.
Anyway I still couldn't use this type = button for my scenario due to I need to get the values from a form submission when this button clicked. If use type = button, I cannot submit and get the values of the form through a $_POST method.
Edit 1
After got help from stack overflow member #Swati, realized that submit will refresh the page and that is why when used submit, modal is showing only for a split second. With her help I modified the code as below and able to solve my problem
$(document).on("click", "#assignQaOa", function(e) {
$('#exampleModalCenter').modal('show');
var sr = $(this).closest(".card-body").find("input[name='srNum']").val();
$('#tagSerial').val(sr);
e.preventDefault();
});
The above code will stop form submission. Also it will grab the input field srNum value and show it in the modal even without submitting form.

Action button with modals and jQuery

I have a problem in my codes. So the idea is I have two modals that triggered when user Click OK or Fail
So when the user click ok the modal is
<div class="modal-body">
This is the confirmation window to PASS all the Quality Control for, <br/><br/>
Project : <b>'.$row['PROJECT_NAME'].'</b><br/>
HeadMark : <b>'.$row['HEAD_MARK'].'</b><br/>
ID : <b>'.$row['ID'].'</b>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" name="acceptButton" id="acceptButton" class="btn btn-success">Confirm PASS!</button>
and when user click FAIL its still the same body but with different button action,
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" name="rejectButton" id="rejectButton" class="btn btn-danger">Confirm REJECT!</button>
</div>
and my jQuery corresponded with those buttons are,
$('#acceptButton').click(function() {
var myData = $('#data_field');
$.post("acceptClass.php",{
acceptProjectName : myData.attr("data_project"),
acceptHeadMark : myData.attr("data_headmark"),
acceptId : myData.attr("data_id")
},function callback(result){
window.location = "update_fabrication_qc_pass.php";
});
});
$('#rejectButton').click(function() {
var myData = $('#data_field');
$.post("rejectClass.php",{
projectName : myData.attr("data_project"),
headMark : myData.attr("data_headmark"),
id : myData.attr("data_id"),
reasonReject : $("#reasonForRejection").val()
},function callback(result){
window.location = "update_fabrication_qc_pass.php";
});
});
Variables that are to be passed are stored in the hidden input,
echo "<input type='hidden' data_project='$row[PROJECT_NAME]' data_headmark='$row[HEAD_MARK]' data_id='$row[ID]' id='data_field'></input>";
So the problem is, all the buttons only work with the (#rejectButton). So even if I click accept button, only the action in the rejectClass.php are applied to the database. It supposed to be when user click acceptButton, actions in the acceptClass.php that are applied.
Please help me, im so confused.

Bootstrap Confirmation Dialog in PHP

How to create a delete confirmation dialog? If 'yes' clicks delete the message, if 'no' clicks cancel delete operation.
Currently I have like this in my view:
Confirm Message
And how to change the dialog box content?
You can't do a confirm or bootstrap confirm in PHP as PHP is server side code.
What you will be after is how to use Javascript to create a confirm box.
Plain Javascript
Using plain standard javascript this would only need a button with a function
HTML
<button onclick="show_confirm()">Click me</button>
javascript
// function : show_confirm()
function show_confirm(){
// build the confirm box
var c=confirm("Are you sure you wish to delete?");
// if true
if (c){
alert("true");
}else{ // if false
alert("false");
}
}
Demo jsFiddle
Bootstrap with jQuery
This way is a little more complex as you are adding in 3rd-party libraries.
To start off with you will need to create a modal to act as your confirm box.
HTML
<div id="confirmModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Delete?</h3>
</div>
<div class="modal-body">
<p>Are you sure you wish to delete?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button onclick="ok_hit()" class="btn btn-primary">OK</button>
</div>
</div>
Same button as before with a little bit of styling
<button class="btn btn-danger" onclick="show_confirm()">Click me</button>
and then the
Javascript
// function : show_confirm()
function show_confirm(){
// shows the modal on button press
$('#confirmModal').modal('show');
}
// function : ok_hit()
function ok_hit(){
// hides the modal
$('#confirmModal').modal('hide');
alert("OK Pressed");
// all of the functions to do with the ok button being pressed would go in here
}
Demo jsFiddle
A simple approach with javascript:
<a onclick="if(!confirm('Are you sure that you want to permanently delete the selected element?'))return false" class="btn btn-large btn-info msgbox-confirm" href="?action=delete">Delete</a>
This way, when user clicks on "Delete", a dialog will ask her/him to confirm. If it is accepted, the page is reloaded with a parameter in the url (change to whatever you need). Otherwise, the dialog is closed and nothing happens.
<script>
function deletechecked()
{
var answer = confirm("Are you sure that you want to permenantly delete the selected element?")
if (answer){
document.messages.submit();
}
return false;
}
</script>
<a href="<?php echo base_url('department/deletedept/'.$row['dept_id']);?>" onclick="return deletechecked();" title="Delete" data-rel="tooltip" class="btn btn-danger">

Add content to div with php dynamically

So I'm making a contact form. When the form is submitted I want to add a success or error message to a Bootstrap modal.
Here is the button that submits the form and opens the modal.
<input class="btn btn-info" type="submit" value="Submit" name="Submit" data-toggle="modal" href="#contactModal"/>
So when the button is clicked it submits the form and opens the modal. Is there a way to add a string of text to the modal dynamically upon success or failure of the script?
Here is the PHP success/failure action currently
if ($success){
print "<meta http-equiv="refresh" content="0;URL=contactthanks.html">";
}
else{
print "<meta http-equiv="refresh" content="0;URL=error.html">";
}
But I want it to add content to the modal instead of adding a <meta> tag that redirects the page
Here is the modal code
<div id="contactModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Thanks!</h3>
</div>
<div class="modal-body">
<p>I'm pretty busy sometimes but I'll try my best to message you back <strong>ASAP</strong>!</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
So how would I print to the inside of a <div> within the modal without refreshing the page or redirecting?
I don't know any PHP or AJAX and I'm just not starting to begin JS and jQuery (two days to be exact)
You cannot submit a form and not have the page refresh. What you most likely want to do is use an AJAX request to your php instead, which will return the success/failure status as JSON, which you will then use to conditionally add content to your div with javascript.
Instead of a form, you will just use a normal <input type="button" /> with an onclick="someFunction" where someFunction makes the AJAX call.
You will want to use jQuery.
Your php would look like
//do something with submitted values
if ($success){
echo json_encode(True);
}
else{
echo json_encode(False);
}
and the AJAX call would be something like
$.ajax({
type: "POST",
url: "dosomething.php",
data: { formValue1 = <get value using jquery>, etc... }
dataType: "json",
success: processData,
error: function(){ alert("failed"); }
});
function processData(data)
{
if(data) {
$("div#divid").html("what you want to add inside the div");
}
}

Categories