Edit PHP/AJAX to deal with DELETE OR EDIT - php

First of all before i show you the code i will explain how my webpage works.
User selects date -> AJAX Calls On Date Change
Resulting PHP data displays in two sections on page.
First Section is Orders Table Contents
Second Section is Items Table Contents (not including the items inside Orders)
What i am trying to add is functionality to 3 buttons that will change the tables dynamically using AJAX.
I currently have working non ajax requests.
Here is the Code:
$(document).ready(function(){
$('.date-picker').change(function(){
$.ajax({
type: 'POST',
url: 'php/getproduct.php',
data: {dateorderpicker: $('.date-picker').val()},
dataType: 'JSON',
success: function(data)
{
$("#cartrow").html(data.result_1);
$("#otheritems").html(data.result_2);
}
});
});
});
PHP file for Current AJAX:
session_start();
include('db_config.php');
$datepicker = $_POST['dateorderpicker'];
$sql = "SELECT * FROM orders WHERE deliveryDate = ? AND customerId = ? ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $datepicker, PDO::PARAM_STR);
$stmt->bindParam(2, $_SESSION['customer_id'], PDO::PARAM_INT);
$stmt->execute();
$container = array();
$data['result_1'] = $data['result_2'] = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$container[] = "'{$row['itemName']}'"; // put them inside a temporary container
$data['result_1'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/edit.php" method="post" class="form-inline pull-right">
<h3>' . $row['itemName'] . '</h3>
<h4>Total Price: $'.$row['price'].'</h4>
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>Our best seller. Full of flavour.</p>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" value="' . $row['qty'] . '">
</div>
</div>
<input type="hidden" name="id" value="'.$row['id'].'">
<button type="submit" name="update" class="btn btn-primary">Update</button>
<button type="submit" name="delete" class="btn btn-primary">Remove</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
if(!empty($container)){
$excluded_names = implode(',', $container);
$sql = "SELECT * FROM item WHERE itemName NOT IN($excluded_names)";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input id="itemname" type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input id="price" type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input id="description" type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input id="qty" type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
else
{
$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
echo json_encode($data);
exit;
Both Update and Delete PHP file:
include('db_config.php');
if (isset($_POST['update']))
{
$qty = $_POST['qty'];
$id = $_POST['id'];
echo $id;
$sql = "UPDATE orders SET qty=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($qty,$id));
header('Location: ../order.php');
}
if (isset($_POST['delete']))
{
$id = $_POST['id'];
$sql = "DELETE FROM orders WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
header('Location: ../order.php');
}
The code above needs to be converted to AJAX, and both sections on the page using ajax should update the table automatically. It might be that you will call the first ajax query to reload the tables correctly?
Thanks for having a look at this.
I am having trouble wrapping my head around how i should get this work.
Alex

It is easy you can give a class (NOTE : yes class ) to your update button and similarly to delete button
Suppose your update button has class "update_task"
but your content was added to DOM after DOM already loaded, so you will need to create two ajax request with DELEGATE Methods for delete and update.
For delegate reference -
http://api.jquery.com/delegate/
// for update
$("body").delegate(".update_task","click",function(){
current_id = $(this).previous("input:hidden").val() // for current update button id,
$.ajax({
type: 'POST',
url: 'php/update_product.php',
data: {id: current_id, othervalues: other_value_of_choice},
dataType: 'JSON',
success: function(data)
{
if(data==1)
{
// what ever you want to do if data has been updated
}
}
});
});

Send AJAX request to PHP for update/delete. Return result of operation (true/false).
If result is true, update/remove from html with javascript(jquery).
By the way, don't use redirect, when you call php via ajax.

Related

Date is being sent as 0000-00-00 and returned as 11/30/-0001 when I use SQL update statement

For some reason when I edit the the date it's being sent as 0000-00-00 to the database. The wrest of the update is working as expected. I have the db rows for the dates set on type: date, default: none, and null: no.
Also tried to remove the values for the date inputs, that didn't do anything either. Please help, thank you!
<?php
include 'db.php';
$WAGE = 14;
$TAX = 0.01;
$SS = 0.062;
$MEDI = 0.0145;
$GOAL = 0.75;
if($_SERVER['REQUEST_METHOD'] === "POST") {
// Variables
$id = htmlspecialchars($_POST['id']);
$begDate = htmlspecialchars($_POST['date1']);
$endDate = htmlspecialchars($_POST['date2']);
$hours = htmlspecialchars($_POST['hours']);
$total = number_format($hours * $WAGE, 2, '.', '');
$taxDeducted = number_format($total * $TAX, 2,'.', '');
$SSDeducted = number_format($total * $SS, '2', '.', '');
$MEDIDeducted = number_format($total * $MEDI, '2', '.', '');
$deducted = number_format($taxDeducted + $MEDIDeducted + $SSDeducted, 2, '.', '');
$total -= number_format($deducted, 2, '.', '');
$save = number_format($GOAL * $total, 2, '.', '');
$date = $_POST['date1'];
// SQL
$sql = "UPDATE hours SET begDate=$date, endDate=$endDate, hours=$hours, deducted=$deducted, save=$save, total=$total WHERE id=$id;";
// EXECUTE
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
<?php
include 'header.php';
include 'db.php';
if(isset($_GET['id'])) :
$id = $_GET['id'];
$sql = "SELECT * FROM hours WHERE id=$id;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $res) :
$begDate = $res['begDate'];
$endDate = $res['endDate'];
$hours = $res['hours'];
endforeach;
?>
<div class="container form bg-light p-5">
<h1 class="text-center my-5">Add a week</h1>
<form action="editForm.php" method="post">
<input type="hidden" name="id" value="<?= $id; ?>" id="id">
<div class="row">
<div class="form-group col-md-5">
<input type="date" name="date1" id="date1" value="<?=$begDate;?>" class="form-control" required>
</div>
<div class="col-md-2 text-center">
<h3>TO</h3>
</div>
<div class="col-md-5 form-group">
<input type="date" name="date2" id="date2" value="<?=$endDate;?>" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-md-3 form-group mx-auto mt-5">
<input class="form-control" value="<?= $hours;?>" type="float" name="hours" id="hours" placeholder="Hours this period" required>
</div>
</div>
<div class="row text-center mt-5">
<div class="form-group col-md-3 mx-auto">
<input type="submit" value="SUBMIT" name="submit" class="btn btn-secondary">
</div>
</div>
</form>
</div>
<?php endif; ?>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'editForm.php',
method: 'post',
data: $('form').serialize()
})
.done(function(res, status) {
if(status == 'success') {
window.location.href = 'index.php';
}
})
.fail(function(res, status) {
if(status == 'error') {
console.log('error');
}
});
})
</script>
<?php include 'footer.php'; ?>

Wanted to add some edit/delete button on my comment system reply part

INDEX.PHP
<body>
<br />
<h2 align="center">Comment System using PHP and Ajax</h2>
<br />
<div class="container">
<form method="POST" id="comment_form" >
<div class="form-group w-50">
<input type="text" name="comment_name" id="comment_name" class="form-control" value="<?php echo $_SESSION['username'];?>" readonly/>
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-inline ">
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Comment" />
</div>
<input type="reset" value="Cancel" class="btn btn-primary" style="margin-left: 5px;">
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();//CONVERTS/STORES THE FORM INTO URL IN CODE
$.ajax({
url:"add_comment.php",//WHERE WILL THE INFO GO ---- OR ---- SENDS REQUEST/GOES TO ADD_COMMENT.PHP and records the info
method:"POST",//FOUND IN THE FORM METHOD, telss what kind of method to use to send the data to server so we use ---POST---
data:form_data,//data: it is the variable/code we used to convert/store the form into url in code
dataType:"JSON",
success:function(data)//Will be called if the sending of data to the comment.php is successful
{ //and success will receive the same data/the form_data from server OR DATA WAS RECEIVED BY SUCCESS
if(data.error != '')//check if there is no error in the process and DISPLAYS THE DATA BELOW
{
$('#comment_form')[0].reset();//as Array, it starts with 0 and the .reset() JUST RESETS THE FORM FIELD/OFF THE AUTO COMPLETE
$('#comment_message').html(data.error);//outputs if there is an error or not
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()//loads all the comment
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)//DISPLAYS DATA BELOW if success
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();// if click it will focus on the comment name
});
});
</script>
ADD_COMMENT.php
<?php
session_start();
//add_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$error = '';
$comment_name = $_SESSION['username'];
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')//if this condition runs then there is no validation error or whatsoever
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
FETCH_COMMENT.php
where the reply part is
<?php
session_start();
//fetch_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
$delete = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>';
$output .= get_reply_comment($connect, $row["comment_id"]);
}
echo $output;
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>

PHP MySQL Ajax form data output

I have a code that I have been trying to run for days without success, could anyone look at it and help figure where I am going crazy?
here is report.js:
$(document).ready(function() {
$('#navReport').addClass('active');
// order date picker
$('#startDate').datepicker();
// order date picker
$('#endDate').datepicker();
$('#getReportForm')
.unbind('submit')
.bind('submit', function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var personId = $('#personId').val();
if (startDate == '' || endDate == '' || personId == '') {
if (startDate == '') {
$('#startDate')
.closest('.form-group')
.addClass('has-error');
$('#startDate').after(
'<p class="text-danger">The Start Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (endDate == '') {
$('#endDate')
.closest('.form-group')
.addClass('has-error');
$('#endDate').after(
'<p class="text-danger">The End Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (personId == '') {
$('#personId')
.closest('.form-group')
.addClass('has-error');
$('#personId').after(
'<p class="text-danger">Person Name is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'text',
success: function(response) {
var mywindow = window.open(
'',
'Child Behavior Management System',
'height=400,width=600'
);
mywindow.document.write('<html><head><title>Report</title>');
mywindow.document.write('</head><body>');
mywindow.document.write(response);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
} // /success
}); // /ajax
} // /else
console.log(personId, startDate, endDate);
return false;
});
});
Here is getReport.php:
<?php
require_once 'core.php';
if($_POST) {
$personId = $_POST['personId'];
$startDate = $_POST['startDate'];
$date = DateTime::createFromFormat('m/d/Y',$startDate);
$start_date = $date->format("Y-m-d");
$endDate = $_POST['endDate'];
$format = DateTime::createFromFormat('m/d/Y',$endDate);
$end_date = $format->format("Y-m-d");
$table = '';
$sql = "SELECT notes.note_id, notes.note_content, notes.person_id,
notes.note_date, notes.note_status, persons.persons_name
FROM notes INNER JOIN persons ON notes.person_id = persons.persons_id
WHERE notes.person_id = '$personId' AND notes.note_date
BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE)
AND notes.note_status = 1"
$query = $connect->query($sql);
$table = '
<table border="1" cellspacing="0" cellpadding="0" style="width:100%;">
<tr>
<th>Date</th>
<th>Note</th>
<th>Resident</th>
</tr>
<tr>';
while ($result = $query->fetch_assoc()) {
$table .= '<tr>
<td><center>'.$result['notes.note_date'].'</center></td>
<td><center>'.$result['notes.note_content'].'</center></td>
<td><center>'.$result['persons.persons_name'].'</center></td>
</tr>';
}
$table .= '
</tr>
</table>
';
echo $table;
}
?>
And here is report.php:
<?php require_once 'includes/header.php'; ?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<i class="glyphicon glyphicon-check"></i> Generate Report
</div>
<!-- /panel-heading -->
<div class="panel-body">
<form class="form-horizontal" action="php_action/getReport.php" method="post" id="getReportForm">
<div class="form-group">
<label for="personId" class="col-sm-2 control-label">Resident</label>
<div class="col-sm-10">
<select type="text" class="form-control" id="personId" placeholder="Resident" name="personId" >
<option value="">~~SELECT~~</option>
<?php
$sql = "SELECT persons_id, persons_name, persons_status FROM persons WHERE persons_status = 1";
$result = $connect->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='".$row[0]."'>".$row[1]."</option>";
} // while ?>
</select>
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="startDate" class="col-sm-2 control-label">Start Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="startDate" name="startDate" placeholder="Start Date" />
</div>
</div>
<div class="form-group">
<label for="endDate" class="col-sm-2 control-label">End Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="endDate" name="endDate" placeholder="End Date" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" id="generateReportBtn"> <i class="glyphicon glyphicon-ok-sign"></i>
Generate Report</button>
</div>
</div>
</form>
</div>
<!-- /panel-body -->
</div>
</div>
<!-- /col-dm-12 -->
</div>
<!-- /row -->
<script src="custom/js/report.js"></script>
<?php require_once 'includes/footer.php'; ?>
I would love to have expert solution to this. I have looked for solution almost the entire night but no joy. The popup is not firing when I select the preferred person, start and end dates based on the query.

mysqli_prepare do not work right

I want to INSERT a few records in my tabel, for this I use mysqli_prepare, bind_param and execute.
In element inspection he gives a 500 internal server error in the params he gives all the data I need.
I hope you guys can help me, here is my code:
PHP
<form id="addFolder">
<div class="form-group col-md-6">
<label for="folderName">Map naam</label>
<input type="text" class="form-control" id="folderName" placeholder="Map naam">
</div>
<div class="form-group col-md-6">
<label for="selectRootFolder">Selecteer root map</label>
<select class="form-control" id="selectRootFolder">
<?php
getRootFolders();
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="selectIcon">Selecteer icon <span class="fa fa-question-circle" id="fa-ask"></span></label>
<input type="text" class="form-control" id="selectIcon" placeholder="fa fa-icon">
</div>
<br><br><br>
<div class="form-group col-md-4">
<div class="checkbox">
<label>
<input type="checkbox" id="isRootMap"> Is root map
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="active"> Actief
</label>
</div>
</div>
<input type="submit" class="btn btn-info" value="Voeg toe" style="float:right; margin-top: 4%;">
</form>
jQuery
$("#addFolder").on("submit", function(e) {
e.preventDefault();
var folderName = $("#folderName").val();
var rootId = $("#selectRootFolder").find("option:selected").data("id");
var isRoot = $("#isRootMap").is(":checked");
var icon = $("#selectIcon").val();
var active = $("#active").is(":checked");
var array = [folderName, rootId, isRoot, icon, active];
$.ajax({
method: "POST",
url: "../admin/handlers/addFolderHandler.php",
data: { data: array }
}).done(function(data) {
if (data == true)
{
window.location.href = "index.php";
}
});
});
Handler
<?php
$gegevens = $_POST['data'];
$folderName = $gegevens[0];
$rootId = ($gegevens[3] == true) ? NULL : $gegevens[1];
$isRoot = ($gegevens[3] == true) ? 1 : 0;
$icon = ($gegevens[3] == true) ? $gegevens[4] : "";
$active = ($gegevens[5] == true) ? "1" : "0";
if (addNewFolder($rootId, $isRoot, $folderName, $icon, $active))
{
echo true;
}
else
{
echo false;
}
?>
Function
function addNewFolder($rootId, $isRoot, $folderName, $icon, $active)
{
global $con;
$query = mysqli_prepare($con, "INSERT INTO folders (parent_id, is_root, `name`, icon, active) VALUES (?, ?, ?, ?, ?)");
$query->bind_param('ddssi', $rootId, $isRoot, $folderName, $icon, $active);
if ($query->execute())
{
return true;
}
else
{
return false;
}
}

Bootstrap modal doesn't respond to my PHP submit form

It doesn't show any error and it doesn't respond when I click Save button. I've tried the PHP insert code in other page without bootstrap and it works I wonder why it's not working in bootstrap modal.
Here's my HTML code:
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<div class="modal-body">
<form method="POST" action="index.php" role="form">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
And this my PHP code:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created)) {
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
Your button Submit is out of <form></form> tag. Kepp it inside <form></form> tag to submit the form.
And also check this line:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created))
Should be:
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby']))
You are checking variables before declaring it, use $_POST instead.
Your code should look like this:
<?php
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby'])) {
$desc1 = $_POST['desc'];
$categ1 = $_POST['category'];
$topicTitle1 = $_POST['topicTitle'];
$created1 = $_POST['createdby'];
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ1', '$topicTitle1', '$desc1', '$created1', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}

Categories