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.
Related
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'; ?>
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;
}
?>
I found two instructions on angularjs (http://softaox.info/category/angularjs/). However, I would like to combine it together - ie displaying, filtering and additionally editing the database directly from the website.
However, I have a problem with connecting two controllers on one page. The database reads, but when I want to edit, delete it, nothing happens. Will you help me solve the problem?
Here is my code
`index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SoftAOX | AngularJS Sorting, Searching and Pagination of Data Table using PHP, MySQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-app="myApp" ng-controller="controller">
<div class="container">
<br/>
<h3 align="center">AngularJS Sorting, Searching and Pagination of Data Table using PHP, MySQL</a></h3>
<br/>
<div class="row">
<div class="col-sm-2 pull-left">
<label>PageSize:</label>
<select ng-model="data_limit" class="form-control">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-sm-6 pull-right">
<label>Search:</label>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Search" class="form-control" />
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12" ng-show="filter_data > 0">
<table class="table table-striped table-bordered">
<thead>
<th>S.No</th>
<th>Name <a ng-click="sort_with('name');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Age <a ng-click="sort_with('age');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Email <a ng-click="sort_with('email');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>
<tr ng-repeat="data in names = (file | filter:search | orderBy : base :reverse) | beginning_data:(current_grid-1)*data_limit | limitTo:data_limit">
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.age}}</td>
<td>{{data.email}}</td>
<td>
<button class="btn btn-success btn-xs" ng-click="update_data(data.id, data.name, data.email, data.age)">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
</td>
<td>
<button class="btn btn-danger btn-xs" ng-click="delete_data(data.id )">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filter_data == 0">
<div class="col-md-12">
<h4>No records found..</h4>
</div>
</div>
<div class="col-md-12">
<div class="col-md-6 pull-left">
<h5>Showing {{ searched.length }} of {{ entire_user}} entries</h5>
</div>
<div class="col-md-6" ng-show="filter_data > 0">
<div pagination="" page="current_grid" on-select-page="page_position(page)" boundary-links="true" total-items="filter_data" items-per-page="data_limit" class="pagination-small pull-right" previous-text="«" next-text="»"></div>
</div>
</div>
<div ng-app="myApp" ng-controller="cont1" ng-init="show_data()">
<div class="col-md-6">
<label>Name</label>
<input type="text" name="name" ng-model="name" class="form-control">
<br/>
<label>Email</label>
<input type="text" name="email" ng-model="email" class="form-control">
<br/>
<label>Age</label>
<input type="text" name="age" ng-model="age" class="form-control">
<br/>
<input type="hidden" ng-model="id">
<input type="submit" name="insert" class="btn btn-primary" ng-click="insert()" value="{{btnName}}">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<script src="myapp.js"></script>
</body>
</html>
myapp.js
var app = angular.module('myApp', ['ui.bootstrap']);
app.filter('beginning_data', function() {
return function(input, begin) {
if (input) {
begin = +begin;
return input.slice(begin);
}
return [];
}
});
app.controller('controller', function($scope, $http, $timeout) {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
$scope.page_position = function(page_number) {
$scope.current_grid = page_number;
};
$scope.filter = function() {
$timeout(function() {
$scope.filter_data = $scope.searched.length;
}, 20);
};
$scope.sort_with = function(base) {
$scope.base = base;
$scope.reverse = !$scope.reverse;
};
});
app.controller("cont1", function($scope, $http) {
$scope.btnName = "Insert";
$scope.insert = function() {
if ($scope.name == null) {
alert("Enter Your Name");
} else if ($scope.email == null) {
alert("Enter Your Email ID");
} else if ($scope.age == null) {
alert("Enter Your Age");
} else {
$http.post(
"insert.php", {
'name': $scope.name,
'email': $scope.email,
'age': $scope.age,
'btnName': $scope.btnName,
'id': $scope.id
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.email = null;
$scope.age = null;
$scope.btnName = "Insert";
$scope.show_data();
});
}
}
$scope.show_data = function() {
$http.get("display.php")
.success(function(data) {
$scope.names = data;
});
}
$scope.update_data = function(id, name, email, age) {
$scope.id = id;
$scope.name = name;
$scope.email = email;
$scope.age = age;
$scope.btnName = "Update";
}
$scope.delete_data = function(id) {
if (confirm("Are you sure you want to delete?")) {
$http.post("delete.php", {
'id': id
})
.success(function(data) {
alert(data);
$scope.show_data();
});
} else {
return false;
}
}
});
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$info = json_decode(file_get_contents("php://input"));
if (count($info) > 0) {
$name = mysqli_real_escape_string($conn, $info->name);
$email = mysqli_real_escape_string($conn, $info->email);
$age = mysqli_real_escape_string($conn, $info->age);
$btn_name = $info->btnName;
if ($btn_name == "Insert") {
$query = "INSERT INTO insert_emp_info(name, email, age) VALUES ('$name', '$email', '$age')";
if (mysqli_query($conn, $query)) {
echo "Data Inserted Successfully...";
} else {
echo 'Failed';
}
}
if ($btn_name == 'Update') {
$id = $info->id;
$query = "UPDATE insert_emp_info SET name = '$name', email = '$email', age = '$age' WHERE id = '$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>
display.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$output = array();
$query = "SELECT * FROM insert_emp_info";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
fetch.php
<?php
$conn = new mysqli('localhost', 'root', '', 'test');
$query = "select distinct id, name, age, email from insert_emp_info order by id";
$result = $conn->query($query) or die($conn->error . __LINE__);
$fetch_data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$fetch_data[] = $row;
}
}
$jResponse = json_encode($fetch_data);
echo $jResponse;
?>`
You can use the same controller for one page. I modified index.php and myapp.js file
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SoftAOX | AngularJS Sorting, Searching and Pagination of Data Table using PHP & MySQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-app="myApp" ng-controller="controller">
<div class="container">
<br/>
<h3 align="center">AngularJS Sorting, Searching and Pagination of Data Table using PHP & MySQL</a></h3>
<br/>
<div class="row">
<div class="col-sm-2 pull-left">
<label>PageSize:</label>
<select ng-model="data_limit" class="form-control">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-sm-6 pull-right">
<label>Search:</label>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Search" class="form-control" />
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12" ng-show="filter_data > 0">
<table class="table table-striped table-bordered">
<thead>
<th>Name <a ng-click="sort_with('name');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Gender <a ng-click="sort_with('gender');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Age <a ng-click="sort_with('age');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Email <a ng-click="sort_with('email');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Phone <a ng-click="sort_with('phone');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Organization <a ng-click="sort_with('organization');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in searched = (file | filter:search | orderBy : base :reverse) | beginning_data:(current_grid-1)*data_limit | limitTo:data_limit">
<td>{{data.name}}</td>
<td>{{data.gender}}</td>
<td>{{data.age}}</td>
<td>{{data.email}}</td>
<td>{{data.phone}}</td>
<td>{{data.organization}}</td>
<td>
<button class="btn btn-success btn-xs" ng-click="update_data(data.id, data.name, data.email, data.age)">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
</td>
<td>
<button class="btn btn-danger btn-xs" ng-click="delete_data(data.id )">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filter_data == 0">
<div class="col-md-12">
<h4>No records found..</h4>
</div>
</div>
<div class="col-md-12">
<div class="col-md-6 pull-left">
<h5>Showing {{ searched.length }} of {{ entire_user}} entries</h5>
</div>
<div class="col-md-6" ng-show="filter_data > 0">
<div pagination="" page="current_grid" on-select-page="page_position(page)" boundary-links="true" total-items="filter_data" items-per-page="data_limit" class="pagination-small pull-right" previous-text="«" next-text="»"></div>
</div>
</div>
</div>
<div class="col-md-6">
<label>Name</label>
<input type="text" name="name" ng-model="name" class="form-control">
<br/>
<label>Email</label>
<input type="text" name="email" ng-model="email" class="form-control">
<br/>
<label>Age</label>
<input type="text" name="age" ng-model="age" class="form-control">
<br/>
<input type="hidden" ng-model="id">
<input type="submit" name="insert" class="btn btn-primary" ng-click="insert()" value="{{btnName}}">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<script src="myapp.js"></script>
</body>
</html>
myapp.js
var app = angular.module('myApp', ['ui.bootstrap']);
app.filter('beginning_data', function() {
return function(input, begin) {
if (input) {
begin = +begin;
return input.slice(begin);
}
return [];
}
});
app.controller('controller', function($scope, $http, $timeout) {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
$scope.page_position = function(page_number) {
$scope.current_grid = page_number;
};
$scope.filter = function() {
$timeout(function() {
$scope.filter_data = $scope.searched.length;
}, 20);
};
$scope.sort_with = function(base) {
$scope.base = base;
$scope.reverse = !$scope.reverse;
};
$scope.btnName = "Insert";
$scope.insert = function() {
if ($scope.name == null) {
alert("Enter Your Name");
} else if ($scope.email == null) {
alert("Enter Your Email ID");
} else if ($scope.age == null) {
alert("Enter Your Age");
} else {
$http.post(
"insert.php", {
'name': $scope.name,
'email': $scope.email,
'age': $scope.age,
'btnName': $scope.btnName,
'id': $scope.id
}
).success(function(data) {
alert("Data Updated Successfully...");
$scope.name = null;
$scope.email = null;
$scope.age = null;
$scope.btnName = "Insert";
$scope.show_data();
});
}
}
$scope.show_data = function() {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
}
$scope.update_data = function(id, name, email, age) {
$scope.id = id;
$scope.name = name;
$scope.email = email;
$scope.age = age;
$scope.btnName = "Update";
}
$scope.delete_data = function(id) {
if (confirm("Are you sure you want to delete?")) {
$http.post("delete.php", {
'id': id
})
.success(function(data) {
alert("Data Deleted Successfully...");
$scope.show_data();
});
} else {
return false;
}
}
});
delete.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$data = json_decode(file_get_contents("php://input"));
if (count($data) > 0) {
$id = $data->id;
$query = "DELETE FROM insert_emp_info WHERE id='$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Deleted Successfully...';
} else {
echo 'Failed';
}
}
?>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$info = json_decode(file_get_contents("php://input"));
if (count($info) > 0) {
$name = mysqli_real_escape_string($conn, $info->name);
$email = mysqli_real_escape_string($conn, $info->email);
$age = mysqli_real_escape_string($conn, $info->age);
$btn_name = $info->btnName;
if ($btn_name == "Insert") {
$query = "INSERT INTO insert_emp_info(name, email, age) VALUES ('$name', '$email', '$age')";
if (mysqli_query($conn, $query)) {
echo "Data Inserted Successfully...";
} else {
echo 'Failed';
}
}
if ($btn_name == 'Update') {
$id = $info->id;
$query = "UPDATE insert_emp_info SET name = '$name', email = '$email', age = '$age' WHERE id = '$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>
fetch.php
<?php
$conn = new mysqli('localhost', 'root', '', 'test');
$query = "select distinct id, name, age, email from insert_emp_info order by id";
$result = $conn->query($query) or die($conn->error . __LINE__);
$fetch_data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$fetch_data[] = $row;
}
}
$jResponse = json_encode($fetch_data);
echo $jResponse;
?>
May use $rootScope to pass the info u need across different controller
Difference between $scope and $rootScope
Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.
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.