How yo insert data with image in AngularJs and PHP mysql - php

I have a CRUD table where I want to display users list with the profile pictures
I'm using AngularJs and Bootstrap
I have added upload file to the form and I'm able to insert to the DB but not able to save the uploaded file to my directory (/uploads)
My index form
<!DOCTYPE html>
<html>
<head>
<title>users</title>
<script src="jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script src="angular-datatables.min.js"></script>
<script src="bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="datatables.bootstrap.css">
</head>
<body ng-app="crudApp" ng-controller="crudController">
<div class="container" ng-init="fetchData()">
<br />
<h3 align="center">user's List</h3>
<br />
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div align="right">
<button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
</div>
<br />
<div class="table-responsive" style="overflow-x: unset;">
<table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
<thead>
<tr><!--data-visible="false"-->
<th width="10%">Image</th>
<th width="35%">First Name</th>
<th width="35%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="name in namesData">
<td>
<img id="{{name.id}}" ng-src="uploads/{{name.photo}}" class="thumbnail" height="50" width="50" >
</td>
<td>{{name.first_name}}</td>
<td>{{name.last_name}}</td>
<td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
<td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="post" ng-submit="submitForm()">
<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">{{modalTitle}}</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" ng-model="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" ng-model="last_name" class="form-control" />
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="photo" ng-model="photo">
<label class="custom-file-label" for="photo">Choose file</label>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="hidden_id" value="{{hidden_id}}" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script>
var app = angular.module('crudApp', ['datatables']);
app.controller('crudController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('fetch_data.php').success(function(data){
$scope.namesData = data;
});
};
$scope.openModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('show');
};
$scope.closeModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('hide');
};
$scope.addData = function(){
$scope.modalTitle = 'Add Data';
$scope.submit_button = 'Insert';
$scope.openModal();
};
$scope.submitForm = function(){
$http({
method:"POST",
url:"insert.php",
data:{'photo':$scope.photo, 'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.form_data = {};
$scope.closeModal();
$scope.fetchData();
}
});
};
$scope.fetchSingleData = function(id){
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'fetch_single_data'}
}).success(function(data){
$scope.photo = data.photo;
$scope.first_name = data.first_name;
$scope.last_name = data.last_name;
$scope.hidden_id = id;
$scope.modalTitle = 'Edit Data';
$scope.submit_button = 'Edit';
$scope.openModal();
});
};
$scope.deleteData = function(id){
if(confirm("Are you sure you want to remove it?"))
{
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'Delete'}
}).success(function(data){
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
};
});
</script>
Insert file which I'm unable to insert images
<?php
//insert.php
include('database_connection.php');
$form_data = json_decode(file_get_contents("php://input"));
$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';
if($form_data->action == 'fetch_single_data')
{
$query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['first_name'] = $row['first_name'];
$output['last_name'] = $row['last_name'];
}
}
elseif($form_data->action == "Delete")
{
$query = "
DELETE FROM tbl_sample WHERE id='".$form_data->id."'
";
$statement = $connect->prepare($query);
if($statement->execute())
{
$output['message'] = 'Data Deleted';
}
}
else
{
if(empty($form_data->first_name))
{
$error[] = 'First Name is Required';
}
else
{
$first_name = $form_data->first_name;
}
if(empty($form_data->last_name))
{
$error[] = 'Last Name is Required';
}
else
{
$last_name = $form_data->last_name;
}
if(empty($error))
{
if($form_data->action == 'Insert')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name
);
$query = "
INSERT INTO tbl_sample
(first_name, last_name) VALUES
(:first_name, :last_name)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
if($form_data->action == 'Edit')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name,
':id' => $form_data->id
);
$query = "
UPDATE tbl_sample
SET first_name = :first_name, last_name = :last_name
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Edited';
}
}
}
else
{
$validation_error = implode(", ", $error);
}
$output = array(
'error' => $validation_error,
'message' => $message
);
}
echo json_encode($output);
?>
Fetch table
<?php
//fetch_data.php
include('database_connection.php');
$query = "SELECT * FROM tbl_sample ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>
I'm using PDO connection
How I can add insert image among the above function

Related

PHP ajax show posts when i click post

i want to make a post form and display the post i made on the list bellow the form. Here is my code. The problem is that when i click the post button the post is stored in the database BUT i have to refresh the page to show the post i did underneath.
<form method="post" id="form_wall">
<textarea name="content" id="content" class="form-control" placeholder="Share any thing what's in your mind"></textarea>
<br>
<div align="right">
<input type="submit" name="submit" id="submit" class="btn btn-primary btn-sm" value="Post" />
</div>
</form>
<h4>Latest POst </h4>
<br>
<div id="website_stuff"> </div>
</div>
</div>
</html>
<script>
$(document).ready(function(){
load_stuff();
function load_stuff()
{
$.ajax({
url:"load_stuff.php",
method:"POST",
success:function(data)
{
$('#website_stuff').html(data);
}
})
}
$('#form_wall').on('submit', function(event){
event.preventDefault();
if ($.trim($('#content').val()).length == 0)
{
alert("Please write something");
return false;
}
else
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data: form_data,
success:function(data)
{
if(data == 'done')
{
$('#form_wall')[0].reset();
load_stuff();
}
}
})
}
});
});
</script>
here is my insert.php code that I call when I hit the post button
<?php
include('database_connection.php');
if(isset($_POST["content"]))
{
$query = "INSERT INTO content (user_id, description) VALUES (:user_id, :description)";
var_dump($query);
$statement = $connect->prepare($query);
$statement->execute(
array(
'user_id' => $_SESSION['user_id'],
'description' => $_POST["content"]
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo 'done';
}
}
?>
Here is the load_stuff.php
<?php
include('database_connection.php');
include('function.php');
if(isset($_SESSION["user_id"]))
{
$output = '';
$query = "SELECT content.content_id, content.user_id, content.description, user_details.user_name FROM content
INNER JOIN user_details
ON user_details.user_id = content.user_id
ORDER BY content_id DESC;
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_rows = $statement->rowCount();
if($total_rows > 0)
{
foreach($result as $row)
{
$like_button ='';
if(!is_user_has_already_like_content($connect, $_SESSION["user_id"], $row["content_id"]))
{
$like_button = '<button type="button" name="like_button" class="btn btn-info btn-xs like_button" data-content_id="'.$row["content_id"].'">Like</button>';
}
$count_like = count_content_like($connect, $row["content_id"]);
$output .='
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> By '.$row["user_name"].'</h3>
<button type="button" name="total_like" id="total_like" class="btn btn-warning btn-xs">'.$count_like.' Like</button>
</div>
<div class="panel-body">
'.$row["description"].'
</div>
<div class="panel-footer" align="right">
'.$like_button.'
</div>
</div>';
}
}
else
{
$output = 'Nobody has share nothing';
}
echo $output;
}
?>

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;
}
?>

Multiple AngularJS controllers in my code

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

Button Add with modal ajax

I'm trying to add a button to add a row in a table adding the values also in a database but when i click the button it refresh my page and doesn't add any row and in my database doesn't add any values.
This is the html form:
<div class="modal fade" id="modaladdWork" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel" aria-hidden="true" >
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modaladdWorkLabel">New Work</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form name="formaddWork">
<div class="modal-body">
<div class="container w-75">
<select id="roleaddWork" name="role" class="form-control" aria-label="Role" aria-describedby="basic-addon1">
<option>Direttore</option>
<option>Vice Direttore</option>
<option>Capo Settore</option>
<option>Dipendente</option>
<option>Stagista</option>
</select> <br>
<input type="number" id="yearaddWork" name="year" min="1900" class="form-control" placeholder="Year" aria-label="Year" aria-describedby="basic-addon1">
<br/>
<input type="text" id="placeaddWork" name="place" class="form-control" placeholder="Place" aria-label="Place" aria-describedby="basic-addon1">
<br />
<?php
$query = "select * from company;";
$result=mysqli_query($connessione, $query);
echo mysqli_error($connessione);
if(mysqli_num_rows($result) > 0){
echo "<div style='float:left';><select id='companyaddWork' name='company' class='form-control' aria-label='Company' aria-describedby='basic-addon1'>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<option>".$row["name"]."</option>";
}
echo "</select></div> <div class='modal-footer'><div style='float:right';>
<button type='button' class='btn btn-primary float-right' data-toggle='modal' data-target='#modalCompany'>
Add Company
</button>
</div></div>";
}
else{
echo "Inserisci prima una compagnia";
}
?>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="submitaddWork" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
and this the javascript code :
function openmodal_addWork()
{
$('#modaladdWork').find('.modal-title').text("Add Work row");
$('#modaladdWork').find(':submit').text("Add");
$('#submitaddWork').click(function() {
op_addWork();
});
$('#modaladdWork').modal('show');
}
function op_addWork()
{
role = $('#roleaddWork').val();
year = $('#yearaddWork').val();
place = $('#placeaddWork').val();
company = $('#companyaddWork').val();
$('#modaladdWork').modal('hide');
$.ajax({
type: "POST",
url: "json/Lavoro.php",
data: {
'role': role,
'year': year,
'place': place,
'company': company
},
success: function(data){
console.log(data);
columns = $(button).closest('tr').find('td');
columns[0].innerHTML = role;
columns[1].innerHTML = year;
columns[2].innerHTML = place;
columns[3].innerHTML = company;
}
});
}
and this one the file "Lavoro.php" that is in the folder "json" :
<?php
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
{
header("Location: ../Principale.php");
exit();
}
if(!isset($_COOKIE["id"]))
{
$json_data = array(
'draw' => 0,
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => 'Laravel Error Handler',
);
$json = json_encode($json_data);
echo $json;
exit();
}
include("../DB.php"); //dati configurazione del database
if(isset($_POST["role"]) && isset($_POST["year"]) && isset($_POST["place"]) && isset($_POST["company"]))
{
$role = mysqli_real_escape_string($connessione, $_POST["role"]);
$year = mysqli_real_escape_string($connessione, $_POST["year"]);
$place = mysqli_real_escape_string($connessione, $_POST["place"]);
$company = mysqli_real_escape_string($connessione, $_POST["company"]);
$result=mysqli_query($connessione,"select company_id from company where name='".$company."';");
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$comp_id=$row[0];
$eeid=$_COOKIE['id'];
$result = mysqli_query($connessione, "INSERT into WORK_EXPERIENCE (role,year,place,company_id,user_id) VALUES ('$role','$year','$place','$comp_id,'$eeid')");
$json_data = array(
//"id" => $id,
"result" => 1
);
$json = json_encode($json_data);
echo $json;
}
?>
What i'm doing of wrong?
Solved. In this line :
$result = mysqli_query($connessione, "INSERT into WORK_EXPERIENCE
(role,year,place,company_id,user_id) VALUES
('$role','$year','$place','$comp_id,'$eeid')")
there was no summit in $comp_id.

jQuery PHP only works with 3 parameters

Heyho,
I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.
Maybe someone could figure out where the mistake is...
This is my code:
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</h1>
<div class="col-sm-8">
<div class="well clearfix">
<div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
<span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
<table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
<th data-column-id="employee_name">Name</th>
<th data-column-id="employee_salary">Salary</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id="add_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_add">
<input type="hidden" value="add" name="action" id="action">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name" name="name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="salary" name="salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="edit_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_id" id="edit_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="edit_name" name="edit_name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#employee_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());
} else {
alert('Now row selected! First select row, then click edit button');
}
}).end().find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
alert(conf);
if(conf){
$.post('response.php', { id: $(this).data("row-id"), action:'delete'}
, function(){
// when ajax returns (callback),
$("#employee_grid").bootgrid('reload');
});
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
});
</script>
response.php
<?php
//include connection file
include_once("connection.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Employee($connString);
switch($action) {
case 'add':
$empCls->insertEmployee($params);
break;
case 'edit':
$empCls->updateEmployee($params);
break;
case 'delete':
$empCls->deleteEmployee($params);
break;
default:
$empCls->getEmployees($params);
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getEmployees($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertEmployee($params) {
$data = array();;
$sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' ); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) ) {
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."' WHERE id='".$_POST["edit_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
}
function deleteEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "delete from `employee` WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
}
?>
There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!
Thank you in advance,
Francis
Yes, you just had to delete the field from your database. It was likely marked as NOT NULL, and when you removed the field from the code, INSERT failed trying to insert a null employee_age :)
You should use your browsers developer tools to check the 'Network' tab for the XHR requests that get fired and have a look at the responses of those.
I think you can debug your way to a working solution from there.
You can use other tools like postman to test you AJAX "API" (response.php) but the developer tools of your browser should be more then sufficient for this ;)

Categories