Bootstrap Modal shows up on one page but not the other? - javascript

I am trying to code a website using Bootstrap. I already have it implemented on one page using a modal (here) and the other page doesn't seem to show the modal (here) on that page, there is a button that can edit the ban details but when I click the edit button, it does nothing.
Also, I am using jQuery for form submissions so that I can redirect to the returned ID, however, I am stuck on how my function can return the ID because using
get_mysql()->fetch_assoc($result)["id"]
causes a 500 internal server error.
Codes can be found below.
ban.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<input type="hidden" id="id" name="id" value="<?php echo $ban["id"] ?>" />
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("add.php", { id: id, uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "ban.php?id=<?php echo data ?>";
});
});
});
</script>
index.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("functions/add.php", { uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "functions/ban.php?id=<?php echo data ?>";
});
});
});
</script>
api.php
<?php
define("key", "redacted");
function get_mysql() {
$mysql = new mysqli("localhost", "redacted", "redacted", "redacted");
if($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = gmdate("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
$result = get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'");
get_mysql()->fetch_array($result);
return $result["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->num_rows > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into `users` (`username`, `password`) values ('$username', '$password'");
}
function get_key() {
return key;
}
?>

I've found the answer thanks to #stain88. I didn't provide the correct link to bootstrap.min.js (facepalm)
Thanks again #stain88.

Related

Submitted Information from a Modal Into mySQL

I was having some problems submitted information from a modal into mySQL, this is what I have tried.
<script>
var cells = document.querySelectorAll('.table-row > td');
var cellIndex = -1;
cells.forEach((e, index) => {
e.addEventListener("click", () => {
//show modal
$('.modal').modal("show");
//update grid
// This is the row number
console.log("Row number: ", index)
cellIndex = index
})
})
function updateTable(e) {
let name, email, phonenumber, tableRow, row;
name = document.getElementById("name").value;
console.log(name, email, phonenumber);
// Get the row that you want
row = cells[cellIndex];
$(row).html(name);
$('.modal').modal("hide");
}
document.getElementById("submit-btn").addEventListener("click", updateTable);
//store in database
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
alert('form was submitted');
}
})
</script>
This is my insert.php:
<?php
$conn = new
mysqli("127.0.0.1","root","password");
if($conn->connect_error){
die("Connection failed: " . $conn-
>connect_error);
}
if(!empty($_POST))
{
$output = '';
$name =
mysqli_real_escape_string($connect,$_POST["name"]);
$phonenumber =
mysqli_real_escape_string($connect,$_POST["phonenumber"]);
$email =
mysqli_real_escape_string($connect,$_POST["email"]);
$query = "INSERT INTO users(name,phonenumber,email) VALUES('$name',
'$phonenumber','$email' )";
}
echo "Connected successfully";
?>
My understanding of the problem is that I need to use ajax to send a request to the web server that would store the information from the modal to the mySQL database with the given query in php. Perhaps I don't have a good understanding of the problem. I am not sure how to get the values from the modal, and in conjuction use ajax to send a post to the server. Any help would be appreciated.
Here is my Modal:
<div class="row">
<div class="col-md-12">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1>Reservation</h1>
</div>
<div class="modal-body">
<input type="text" name="field1" placeholder="Name" id="name">
<input type="text" name="field2" placeholder="Email" id="email">
<input type="text" name="field3" placeholder="PhoneNumber" id="phonenumber">
</div>
<div class="modal-footer">
<input id="submit-btn" name="submit" class="btn submit" value="Submit">
<input class="btn btn-default" data-dismiss="modal" value="Close">
</div>
</div>
</div>
</div>
</div>
</div>

How to check if id selector has data or not in bootstrap modal

I am trying to check if an id selector like (ajax response) has some data in it or not in Bootstrap modal. Based on the result I want to display input field otherwise the input field for data update should not be displayed.
I don't want to display blank input field for data update.
<body>
<!-- The Update Modal -->
<div class="modal" id="update_notes">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Notes Editor</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group"><input type="text" id="up_heading" class="form-control" placeholder="Heading"></div>
<?php
if('.$("#up_notes1").val().' != ""){
>
<div class="form-group"><input type="text" id="up_notes1" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
<?php
if('.$("#up_notes2").val().' != ""){
?>
<div class="form-group"><input type="text" id="up_notes2" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
<?php
if('.$("#up_notes3").val().' != ""){
?>
<div class="form-group"><input type="text" id="up_notes3" class="form-control" placeholder="Notes Details"></div>
<?php
}
?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal" onclick="updatenotesdetails()">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="hidden" id="hidden_notes_id">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
load_data();
function load_data(page, query = '')
{
$.ajax({
url:"notes_sa_add_fetch.php",
method:"POST",
data:{page:page, query:query},
success:function(data)
{
$('#dynamic_content').html(data);
}
});
}
//Edit and Update record
function GetnotesDetails(notesid){
$('#hidden_notes_id').val(notesid);
$.post(
"notes_sa_add_bk.php",{
notesid:notesid
},
function(data, status){
var notes = JSON.parse(data);
$('#up_heading').val(notes.HEADING);
$('#hidden_notes_hid').val(notes.HID);
$('#hidden_notes_pid').val(notes.PID);
$('#up_notes1').val(notes.P_1);
$('#up_notes2').val(notes.P_2);
$('#up_notes3').val(notes.P_3);
}
);
$('#update_notes').modal("show");
}
function updatenotesdetails(){
var heading_up = $('#up_heading').val();
var notestype_up = $('#up_notestype').val();
var notes1_up = $('#up_notes1').val();
var notes2_up = $('#up_notes2').val();
var notes3_up = $('#up_notes3').val();
var hidden_notes_id_up = $('#hidden_notes_id').val();
$.post(
"notes_sa_add_bk.php",{
hidden_notes_id_up:hidden_notes_id_up,
heading_up:heading_up,
notestype_up:notestype_up,
notes1_up:notes1_up,
notes2_up:notes2_up,
notes3_up:notes3_up
},
function(data, status){
$('#update_notes').modal("hide");
readRecords();
}
);
}
</script>
</body>
Thanks in advance.
Please change the code to the following to check if up_notes1, up_notes2 and up_notes3 are empty:
<!-- Modal body -->
...
<?php
$up_notes1 = $_POST['up_notes1'];
if(isset($up_notes1) && $up_notes1 != "") {
>
<div class="form-group">
<input type="text" id="up_notes1" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes1; ?>">
</div>
<?php
}
?>
<?php
$up_notes2 = $_POST['up_notes2'];
if(isset($up_notes2) && $up_notes2 != "") {
?>
<div class="form-group">
<input type="text" id="up_notes2" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes2; ?>">
</div>
<?php
}
?>
<?php
$up_notes3 = $_POST['up_notes3'];
if(isset($up_notes3) && $up_notes3 != "") {
?>
<div class="form-group">
<input type="text" id="up_notes3" class="form-control" placeholder="Notes Details" value="<?php echo $up_notes2; ?>">
</div>
<?php
}
?>
...
If you want to check if they are empty before post to server, add the following code to updatenotesdetails():
function updatenotesdetails() {
var heading_up = $('#up_heading').val();
var notestype_up = $('#up_notestype').val();
var notes1_up = $('#up_notes1').val();
var notes2_up = $('#up_notes2').val();
var notes3_up = $('#up_notes3').val();
var hidden_notes_id_up = $('#hidden_notes_id').val();
if(heading_up == '' || notestype_up == '' || notes1_up == '' || notes2_up == '' || notes3_up == '' || hidden_notes_id_up == '') {
alert('Please fill in all fields!');
return false;
} else {
// Post data to server...
}
}
Don't forget to rate if it was helpful.
Thanks.

Pass Value From URL Link To Form Field

I have a link in a table from results of an SQL query. Each row has a unique ID. I define this in my script as $id
What I am trying to do is have a link that opens up a form in a modal box where a user can insert a note about that row and save it. This then gets inserted into DB with ID, rowID, Note, Date
echo "<td class='agentid'>" . $id. "<br><a href='#notes' data-toggle='modal' data-row-id='".$id."'>Add Note</a></td>" ;
The modal:
<div class="modal" id="notes">
<div class="modal-dialog">
<div class="modal-content">
<form action="postnote.php" method="post">
<div class="modal-body">
<div class="modal-header">
<h4 class="modal-title">Add a Note</h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
<p>Note will show when page is refreshed</p>
<label for="fname">Note: </label>
<input type="hidden" name="rowID" value=""/>
<input class="form-control" type="text" name="notes" value="<?php echo date('m/d/Y h:i'); ?> - "/>
<div class="modal-footer">
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$('#notes').on('show.bs.modal', function(e) {
var row = $(e.relatedTarget).data('row-id');
$(e.currentTarget).find('input[name="rowID"]').val(row);
});
</script>
my postnote.php
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
$pdo = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, MYSQL_USER,MYSQL_PASSWORD,$pdoOptions);
$data = [
'notes' => $_POST['notes'],
'id' => $_POST['rowID'],
];
$sql = "INSERT INTO act_recon_notes (note_id, note) Values(:id, :notes)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
header('Location: ' . $_SERVER['HTTP_REFERER']);
I have this exact script on another page and it is working just fine. This does not post the $id into the form. So after submit it is a blank rowID value in the DB.
The issue was I had conflicting JS on the page. I removed the JS that was not needed for this page and the issue resolved.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

Why my succes-msg or error-msg are not display?

well, in my js files, i'm trying to display success-ms or error-msg. I don't understang why my div #error-msg or #success-msg doesn't appear.
Here my js code. If user clicks on confirm, data are sent to process.php to insert the keyword in my mysql table
$(function()
{
$('#alert-change').click(function(event){
$("#error-msg12").html('');
$("#success-msg12").html('');
event.preventDefault();
$.post('include/process.php',$('#alert-change-form').serialize(),function(resp)
{
if (resp['status'] == true)
{
$("#success-msg12").html(resp['msg']+"");
$("#success-msg12").show();
}
else
{
var htm = '<button data-dismiss="alert" class="close" type="button">×</button>';
$.each(resp['msg'],function(index,val){
htm += val+" <br>";
});
$("#error-msg12").html(htm);
$("#error-msg12").show();
}
},'json');
});
});
My form
<div id="myModal_alert" class="modal fade">
<div class="modal-dialog modal-login1">
<div class="modal-content">
<form name="alert-change-form" id="alert-change-form" method="post">
<div class="modal-header">
<h4 class="modal-title">Add a keyword.</h4>
<div class="alert" id="error-msg12">
</div>
<div class="alert alert-success" id="success-msg12">
</div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="process" name="process" value="4">
<input type="hidden" id="first_name" value ="<?= $_SESSION['name']?>" class="form-control" name="first_name" minlength="3" maxlength="10" placeholder="" class="login" />
<div class="form-group">
<div class="clearfix">
<label>add a keywordt.</label>
</div>
<input type="text" id="kw" class="form-control" name="alert" placeholder="" class="kw" required />
</div>
</div>
<div class="modal-footer">
<button class="button btn btn-primary btn-large" id="alert-change">Confirmer</button>
</div>
</form>
</div>
</div>
</div>
and my process.php file
if ($_POST['process'] == '4') {
$error = array();
$res = array();
$success = "";
$alert = mysql_real_escape_string($_POST['alert']);
echo $_POST['first_name'];
echo $alert;
// errors
if (!preg_match("#^[a-z0-9_]+$#", $alert))
{
$error[] = 'error 1';
}
if (strlen($alert) < 2)
{
$error[] = 'error 2';
}
$sql = "SELECT * FROM users_alert WHERE user = :user AND kw = :alert";
$req = $bdd->prepare($sql);
$req->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$req->bindParam(':alert', $alert, PDO::PARAM_STR);
$req->execute();
$resultat = $req->fetchAll();
if (count($resultat))
{
$error[] = 'error 3';
}
if(count($error)>0)
{
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
// on exécute
$sqlQuery = "INSERT INTO users_alert (user,kw) VALUES (:user,:kw)";
$run = $bdd->prepare($sqlQuery);
$run->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$run->bindParam(':kw', $alert, PDO::PARAM_STR);
$run->execute();
$resp['msg'] = "success1";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
I've tried 4/5 things, in vain.
Somebody has an idea ?
Can you delete them in the process.php file and try again?
echo $_POST['first_name'];
echo $alert;
If this is not working, you should capture the post values ​​you sent to the process.php file and go step by step.

Returning json array does not shows up result on the calling script

I am posting a value on a modal dialog box and then some database operations. Now I am returning a value through
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
Is this a right way? All the database operations are performed correctly but console.log(result) does not show anything on the calling script. Something's wrong with the couple of lines above. It would be very helpful if somebody points out the error.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
And my browser tool shows,
Loading failed for the <script> with source “http://localhost/project/js/compatibility.js”.
studyChapterpdf.php:54
Use of captureEvents() is deprecated. To upgrade your code, use the DOM 2 addEventListener() method. For more help http://developer.mozilla.org/en/docs/DOM:element.addEventListener
studyChapterpdf.php:240:36
ReferenceError: fakewaffle is not defined[Learn More]
studyChapterpdf.php:492:3
Warning: Setting up fake worker.
pdf.js:1489:5
progress
Object { loaded: 131072, total: 551963 }
bootstrap-pdf-viewer.js:563:9
progress
Object { loaded: 551963, total: 551963 }
bootstrap-pdf-viewer.js:563:9
page=1 - getOperatorList: time=522ms, len=755
Found out the reason for it. There was an uncommented line left in one of the included files. So, the response was having the whole commented line as well as the actual return status==active. Fixed it. Thanks everyone for guiding.

Categories

Resources