Add content to div with php dynamically - php

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");
}
}

Related

I want to make a popup appear in 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

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.

Getting bootstrap modal to run on query failure

I am trying to get a modal to display if a user enters a username which already exists. I am using PDO to execute the queries and I am using if($var->rowCount() > 0) to check whether or not the username already exists, I have also stored a variable called $modalHead to store the string that should be displayed for the modal head as well as $modalMsg as the text that should be used for the content of the modal, the use of these can be found below:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><?php echo $modalHead; ?></h4>
</div>
<div class="modal-body">
<p><?php echo $modalMsg; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
However, I am having issues with trying to trigger jQuery code when the PHP if statement is true. I have tried echoing the code inside of php like so:
echo '<script> SHOW MODAL WITH JQUERY </script>';
I have also tried storing a variable such as $showModal which either has the value true or false. I then tried to get this value using var show = "<?php echo $showModal; ?>" and tried to detect the value, however, that also failed to show the modal. The only luck i've had was when I got it show up earlier but the page refresh on submit stopped it from showing completely before the page reloaded. I've also played around with the idea that I could redirect the user to something like register.php?error=... to detect when the modal should be shown.
Any help to combat this issue would be appreciated, thanks!
Since the module is waiting for user input, and the checking is done server-side, the best way to do it is to do a post request using JQuery, and load the module according to the results that your PHP page returns.
In your client page ( html/js)
<script>
$("#submit").click(function({
$.ajax({
method: "POST",
url: "some.php",
data: { username: "username", password: "password" }
})
.done(function( msg ) {
if(msg=="0"){
$(".modal-title").html("Registration Error!");
$(".modal-body p").html("Username already exists!");
$("#modal").show();
}else{
//redirect here
}
});
});
</script>
and in your some.php file
//Query here
//depending on query result echo 0 if error and 1 if success
Found the solution!
I did it so on say something like a duplicate username, I did it so it redirected to the page + ?error= then gave a unique error code to each type of error. Then I used a javascript function to get the error id and then display the modal appropriate for the error. I ran this function on the body load and also added onclick to the close buttons to the modal to run a function which redirects back to the page without ?error=
Thanks everyone for their help!

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">

Categories