how to update the data using angularjs+php? - php

I need to update the data from MySQL DB using AngularJS + PHP.
Dashboard.html is my first page I just give only two field: name and position, and I fetch the data from DB using ng-repeat after fetch the code the user will click the edit button it will redirect to the edit.html page with the same fields: name and position. Help me to fetch that name and position data in edit.html page
Dashboard.html
<div ng-app="myapp" ng-controller="usercontroller">
<table>
<th>Name</th>
<th>Position</th>
<tbody>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.position}}</td>
<td>
<span class="glyphicon glyphicon-edit" ng-click="updateData(x.name, x.position)" ></span>
</td </tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var app = angular.module("myapp", []);
app.controller("usercontroller", function($scope, $http) {
$scope.updateData = function(name, position) {
$scope.name = name;
$scope.position = position;
$scope.btnName = "Update";
}
});
</script>
This is my edit.html page and am using ng-model to bind the data from
dashboard.html, but it is not binding. And I click the update button the data have to update with id, and I mentioned my PHP file also.
My DB name sample and table named demo.
Edit.html
<div ng-app="myapp" ng-controller="EditController">
<form name="form">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" ng-model="name" /> {{name}}
</div>
<div class="form-group">
<label for="position">Position</label>
<input class="form-control" type="text" name="position" ng-model="position" />
</div>
<input type="submit" name="btnUpdate" class="btn btn-success" ng-click="update_data()" value="{{btnName}}">
</form>
<script>
var app = angular.module("myapp", []);
app.controller("EditController", function($scope, $http) {
$scope.btnName = "Update";
$scope.update_data = function() {
$http.post(
"edit.php", {
'name': $scope.name,
'position': $scope.position,
'btnName': $scope.btnName
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.position = null;
$scope.btnName = "Update";
});
}
});
</script>
Edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "sample");
$data = json_decode(file_get_contents("php://input"));
if (count($data) > 0) {
$name = mysqli_real_escape_string($connect, $data->name);
$position = mysqli_real_escape_string($connect, $data->position);
$btn_name = $data->btnName;
if ($btn_name == 'Update') {
$id = $data->id;
$query = "UPDATE demo SET name = '$name',position = '$position' WHERE id = '$id'";
if (mysqli_query($connect, $query)) {
echo 'Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>

You have two different controllers: usercontroller and EditController. Once you leave one and enter another, you lose your bindings. So ng-model="name" in once controller is completely different from ng-model="name" in the second controller.
To make sure that they are the same, you need to create a service that will share data between controllers. You can make it like a simple storage service without any bindings.
When you want to update the data, you need to save it in the service as well. And whenever you want to edit it, you need to pull that data out of it, and populate your models.
Example of such service:
app.service("storageService", function() {
this.data = {};
this.set = function(name, position, btnName) {
this.data = {
"name": name,
"position": position,
"btnName": btnName
};
}
this.get = function() {
return this.data;
}
this.clear = function() {
this.data = {
"name": null,
"position": null,
"btnName": null
};
}
})
The you can inject it into your controllers and use it's functions:
usercontroller
app.controller("usercontroller", function($scope, $http, storageService) { // <-- note the injection
$scope.updateData = function(name, position) {
$scope.name = name;
$scope.position = position;
$scope.btnName = "Update";
storageService.set($scope.name, $scope.position, $scope.btnName); // saving data
}
});
EditController
app.controller("EditController", function($scope, $http, storageService) {
var d = storageService.get(); // loading data
$scope.name = d.name;
$scope.position = d.position;
$scope.btnName = "Update"; // = d.btnName;
$scope.update_data = function() {
$http.post(
"edit.php", {
'name': $scope.name,
'position': $scope.position,
'btnName': $scope.btnName
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.position = null;
$scope.btnName = "Update";
});
}
});

Related

ng-blur action not being triggered

An input field is being generated by ng-repeat. The input tag includes ng-model and ng-blur. The ng-blur action is not triggered and the console doesn't show any errors.
The HTML is generated by a Zend Framework 3 app. I'm using angularjs 1.7.8 and jquery 3.1.0.
Here is the body of the web page
<body ng-app='byDomainApp' ng-controller='ByDomainCtrl'>
<center>
<h2>Maintenance By Domain</h2>
</center>
<p>You may edit/correct any of the following details. Note that an
update will be ignored if the email address is changed to one that has
been tried previously.</p>
<div class='row'>
<div class='col-xs-3'>
Choose a domain: <select class='form-control' ng-model="myDomain"
ng-change="domainUsers(myDomain)"
ng-options="domain.domain_name for domain in domains track by domain.domain_id"></select>
<p ng-hide 'message=null' >
<br> <br>{{message}}
</p>
</div>
</div>
<div class='row'>
<div class='col-xs-2'>Name</div>
<div class='col-xs-2'>Email</div>
<div class='col-xs-2'>Company</div>
<div class='col-xs-2'>Job title</div>
<div class='col-xs-2'>Country</div>
<div class='col-xs-2'>Confirmed?</div>
</div>
<div ng-repeat="user in users" class='row'>
<div class='col-xs-2'>
<input ng-model="user.user_name" ng-blur="updateUser(user)">
</div>
<div class='col-xs-2'>{{user.user_email}}</div>
<div class='col-xs-2'>{{user.user_company}}</div>
<div class='col-xs-2'>{{user.user_jobtitle}}</div>
<div class='col-xs-2'>{{user.user_country}}</div>
<div class='col-xs-2'>{{user.user_confirmed}}</div>
</div>
The Javascript angular code
angular.module('byListApp', []).constant("listUrl",
"http://elms2.com/list-rest").constant("userUrl",
"http://elms2.com/user-rest").controller(
"ByListCtrl",
function($scope, $http, listUrl, userUrl) {
$scope.hide = true;
$scope.showMessage = false;
$http.get(listUrl + '/' + ownerId).then(function(response) {
$scope.lists = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
$scope.listUsers = function(list) {
$scope.message = '';
$scope.hide = true;
$scope.showMessage = false;
// $scope.booksFound[0].message = '';
$http.get(userUrl + '/byList:' + list.list_id).then(
function(response) {
$scope.users = response.data;
});
};
});
angular.module('byDomainApp', []).constant("domainUrl",
"http://elms2.com/domain-rest").constant("userUrl",
"http://elms2.com/user-rest").controller(
"ByDomainCtrl",
function($scope, $http, domainUrl, userUrl) {
$scope.hide = true;
$scope.showMessage = false;
$http.get(domainUrl).then(function(response) {
$scope.domains = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
$scope.domainUsers = function(domain) {
$scope.message = '';
$scope.hide = true;
$scope.showMessage = false;
$http.get(userUrl + '/byDomain:' + domain.domain_id).then(
function(response) {
$scope.users = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
};
$scope.updateUser = function(user) {
$http.get(userUrl + '/updateUser:' + user).then(
function(response) {
$scope.userData = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
};
});
The list of domains is generated correctly and the ng-repeat fills with the correct data when a domain is selected. However nothing happens when the input field contents are edited and then loses focus. I can prove that by deleting the updateUser function from the angular code or replacing the ng-blur action with an alert or similar.
This is now working and I can't explain why as nothing has changed.

AngularJS Inserting and displaying from database

I am using AngularJS to insert and then display data from my MYSQL database. Displaying the data was successfully working but then when I added the inserting feature the display feature broke. Now inside the table which is supposed to be displaying the data I am just getting the variable e.g {{x.ID}} or {{x.Make}}.
Any help is appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title> Display data from Mysql Database Using AngularJS with PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div class="container">
<h1 align="center">Insert Data Into Database using Angular JS with PHP Mysql</h1>
<div ng-app="sa_insert" ng-controller="controller">
<label>ID</label><input type="text" name="ID" ng-model="name" class="form-control"><br/>
<label>Make</label><input type="text" name="Make" ng-model="Make" class="form-control"><br/>
<label>Model</label><input type="text" name="Model" ng-model="Model" class="form-control"><br/>
<label>Reg</label><input type="text" name="Reg" ng-model="Reg" class="form-control"><br/>
<label>Owner</label><input type="text" name="Owner" ng-model="Owner" class="form-control"><br/>
<label>Image</label><input type="text" name="Image" ng-model="Image" class="form-control"><br/>
<input type="submit" name="insert" class="btn btn-success" ng-click="insert()" value="Insert">
</div>
</div>
<!-- Script -->
<script>
var app = angular.module("sa_insert", []);
app.controller("controller", function($scope, $http) {
$scope.insert = function() {
$http.post(
"statementinsert.php", {
'ID': $scope.ID,
'Make': $scope.Make,
'Model': $scope.Model,
'Reg': $scope.Reg,
'Owner': $scope.Owner,
'Image': $scope.Image,
}
).success(function(data) {
alert(data);
$scope.ID = null;
$scope.Make = null;
$scope.Model = null;
$scope.Reg = null;
$scope.Owner = null;
$scope.Image = null;
});
}
});
</script>
<div class="container">
<h3 align="center">Display data from Mysql Database Using AngularJS with PHP</h3>
<div ng-app="sa_display" ng-controller="controller" ng-init="display_data()">
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Make</th>
<th>Model</th>
<th>Age</th>
<th>Reg</th>
<th>Owner</th>
<th>Image</th>
</tr>
<tr ng-repeat="x in names">
<td>{{x.ID}}</td>
<td>{{x.Make}}</td>
<td>{{x.Model}}</td>
<td>{{x.Age}}</td>
<td>{{x.Reg}}</td>
<td>{{x.Owner}}</td>
<td>{{x.Image}}</td>
</tr>
</table>
</div>
</div>
<!-- Script -->
<script>
var app = angular.module("sa_display", []);
app.controller("controller", function($scope, $http) {
$scope.display_data = function() {
$http.get("statement.php")
.success(function(data) {
$scope.names = data;
});
}
});
</script>
</body>
</html>
You have created the module two times for two controllers. Its not the right way of creating AngularJS module and controllers. Create the module once and add necessary contollers in to it.
The javascript code should like following:
<script>
var app = angular.module("saAppModule", []);
app.controller("insertController", function($scope, $http) {
$scope.insert = function() {
$http.post(
"statementinsert.php", {
'ID': $scope.ID,
'Make': $scope.Make,
'Model': $scope.Model,
'Reg': $scope.Reg,
'Owner': $scope.Owner,
'Image': $scope.Image,
}
).success(function(data) {
alert(data);
$scope.ID = null;
$scope.Make = null;
$scope.Model = null;
$scope.Reg = null;
$scope.Owner = null;
$scope.Image = null;
});
}
});
app.controller("disPlayController", function($scope, $http) {
$scope.display_data = function() {
$http.get("statement.php")
.success(function(data) {
$scope.names = data;
});
}
});
</script>
And you have to use these controller appropriate way under separate template.

Angular JS md-datepicker

I want to insert my md-datepicker value into PHP database but while inserting the error is that the data is undefined, in case of Date. How should I insert the value of md-datepicker inside the PHP Page.
reservation.html
<div id="reservation" class="reservation" ng-controller="ReservationController">
<h2><i>Reservations</i></h2>
<div class="datepicker" ng-controller="DatePickerController">
<section layout="row" layout-sm="column" layout-align="center center" layout-wrap required>
<md-datepicker ng-model="ctrl.myDate" md-placeholder="Enter Date" md-open-on-focus required></md-datepicker>
</div>
<input type='text' class='myBox' placeholder="Enter your name..." ng-model="username">
<input type='text' class='myBox' style="margin-left:100px;" placeholder="Enter your mobile number..." ng-model="mobile_number">
<div class="book">
<button type="submit" class="btn btn-primary btn-lg" ng-click="insertData()">Book Your Meal</button>
</div>
</div>
datepicker.js
app.controller('DatePickerController',['$scope',function($scope){
this.myDate = new Date();
var [] newDate = ctrl.MyDate.Split(T);
string finalDate = newdate[0];
$scope.myDate = finalDate;
this.isOpen = false;
}]);
reservation.js
app.controller("ReservationController",['$scope', '$http', function ($scope,$http) {
$scope.insertData = function(){
//window.location.href='index.html#/menu';
$http.post('database/push_Reservation.php',{'username':$scope.username, 'mobile_number': $scope.mobile_number, 'mydate': $scope.myDate})
.then(function(data){
console.log(data);
});
}
}]);
DatepickerController:
app.controller('DatePickerController',['$scope',function($scope){
this.myDate = new Date();
var [] newDate = ctrl.MyDate.Split(T);
string finalDate = newdate[0];
$scope.myDate = finalDate;
this.isOpen = false;
$scope.$emit('response', $scope.myDate);
}]);
ReservationController:
app.controller("ReservationController",['$scope', '$http', function ($scope,$http) {
$scope.$on('response', function (evnt, data) {
$scope.myDate = data;
});
$scope.insertData = function(){
//window.location.href='index.html#/menu';
$http.post('database/push_Reservation.php',{'username':$scope.username, 'mobile_number': $scope.mobile_number, 'mydate': $scope.myDate})
.then(function(data){
console.log(data);
});
}
}]);

Update DB::table from passed object of array in laravel

In laravel, I'm trying to update several tables and rows. i have items that are to be received and checked by 2 different users.
in my show.blade.php, i have this verify button and submit button depending on the user.
#if (($current_user_id != $saved_receiver_id) && ($saved_receiver_id != $not_yet_received))
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_by" class="pull-left" >Received by:</label> <span class="fa"></span>
<input type="hidden" name="receiver_id" value="{{ $saved_receiver_id }}" >{{ $receiver_username }}</input>
</div>
</div>
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_date" class="pull-left" >Received date:</label> <span class="fa"></span>
<input type="hidden" name="received_date" value="{{ $received_date }}" >{{ $received_date }}</input>
</div>
</div>
<input type="hidden" name="purchase_orders_id" value="{{ $purchase_order_number }}">
<input type="hidden" name="checker_id" value="{{ $current_user_id }}">
<div class="row padder m-b">
<div class="col-md-12">
<label for="final_checker_remarks" class="pull-left" >Final Remarks</label>
<textarea class="form-control col-md-12" name="final_checker_remarks" value="{{ $final_checker_remarks }}" id="final_checker_remarks">{{ $final_checker_remarks }}</textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="button" class="pull-right btn btn-success btn-sm submit-btn" id="update-form-submit" data-action="verified">Verified</button>
</div>
</div>
#else
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm submit-btn" id="update-form-submit" data-action="submit">Submit List</button>
</a>
</div>
#endif
now in my ReceivesController.php, i have this postUpdate function,
public function postUpdate(Request $request)
{
if (! $request->ajax()) {
abort(404);
}
$items = json_decode($request->items);
$action = json_decode($request->action);
if(!count($items) && !count($items->purchase_item_id)){
return false;
}
$cnt = count($items->purchase_item_id);
// Receiver Submit function
if ($action == "submit") {
// Saves the received id of the one who received to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'receiver_id' => $items->receiver_id,
]);
// Saves the quantity received and receiver remarks to purchase items table
for($i=0; $i<$cnt; $i++){
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quantity_received' => $items->quantity_received[$i],
'receiver_remarks' => $items->receiver_remarks[$i],
]);
}
// Items Received Success Message
$message = 'Items Received';
}
// QA or Checker Finalize function
else {
// Saves the checker id, and final checker remarks of the one who made the QA to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'checker_id' => $items->checker_id,
'final_checker_remarks' => $items->final_checker_remarks,
]);
// Saves the quality received and checker remarks to purchase items table
for($i=0; $i<$cnt; $i++){
$quality_received = $items->quality_received;
if(is_array($items->quality_received)){
$quality_received = $items->quality_received[$i];
}
$checker_remarks = $items->checker_remarks;
if(is_array($items->checker_remarks)){
$checker_remarks = $items->checker_remarks[$i];
}
$quantity_received = $items->quantity_received;
if(is_array($items->quantity_received)){
$quantity_received = $items->quantity_received[$i];
}
$receiver_remarks = $items->receiver_remarks;
if(is_array($items->receiver_remarks)){
$receiver_remarks = $items->receiver_remarks[$i];
}
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quality_received' => $quality_received,
'checker_remarks' => $checker_remarks,
'quantity_received' => $quantity_received,
'receiver_remarks' => $receiver_remarks,
]);
// Increments or Adds the quantity received to items table
DB::table('items')
->where('purchase_items.id', $items->purchase_item_id[$i])
->join('purchase_items', 'items.id', '=', 'purchase_items.item_id')
->increment('items.measurement', $items->quantity_received[$i]);
}
/ / Items Finalized Success Message
$message = 'Items Verified';
}
// Returns Success Message
return response()->json([
'success' => true,
'message' => $message
]);
}
Now my problem is only the first letter of the word that is typed in the input area are being saved, and in others they are not saved, however, in other, it can be saved. I know its weird, but i cant find which part of my codes is doing such result, what is it that i need to do for me to update my tables correctly? Thanks in advance for the help.
Update: Here is my receive-form-function.js
/* ========================================================================
* Initialize Pages
* ======================================================================== */
$(initialPages);
/* ========================================================================
* Major function
* ======================================================================== */
/* ==== function to init this page === */
function initialPages($) {
// if($('#receives-list-table').length){
// DataTables("#receives-list-table", "receives");
// }
if($('#receiveItems-list-table').length){
$("#receiveItems-list-table").DataTable({
responsive: true,
ordering: false,
});
}
$('#update-form-submit').on('click', function(){
var action = $(this).data('action');
updateReceiveItem(action);
});
clearInputs();
}
/* === dataTables === */
function DataTables(selector, controller) {
$(selector).DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: url+'/'+controller+'/paginate'
});
}
function updateReceiveItem(action){
loadingModal('show','Updating ....');
ajaxCsrfToken();
var data = $('#receiveItems_id').serializeArray();
data = JSON.stringify(data);
// data = JSON.parse(data);
data = JSON.stringify($('#receiveItems_id').serializeObject());
// data = $('#receiveItems_id').serializeObject();
$.ajax({
url: url+'/receives/update',
type: 'post',
data: {'items':data, 'action': action},
dataType: 'json',
complete: function() {
loadingModal('close');
},
error: function(result) {
},
success: function(result) {
successAlert('#receiveItems-result', result.message);
// if (result.success) {
// $('input, select, textarea').attr('disabled', true);
// } else {
// alert(result.message);
// }
}
});
console.log(data);
return false;
}
/**
* Use to format serialize data and convert to json data
*
* Usage: JSON.stringify($('form').serializeObject())
*/
$.fn.serializeObject = function() {
var o = Object.create(null),
elementMapper = function(element) {
element.name = $.camelCase(element.name);
return element;
},
appendToResult = function(i, element) {
var node = o[element.name];
if ('undefined' != typeof node && node !== null) {
o[element.name] = node.push ? node.push(element.value) : [node, element.value];
} else {
o[element.name] = element.value;
}
};
$.each($.map(this.serializeArray(), elementMapper), appendToResult);
console.log(o);
return o;
};
my $.fn.serializeObject = function() above seems to have the bug, i tried using another $.fn.serializeObject = function(), and it gave me the json object that i want. here is the $.fn.serializeObject = function() that i am using now.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Make checkboxes choose content to present from a database

I'm creating a website where the user is supposed to check a couple of checkboxes and then the site will present the data in a table.
I have been looking at this "guide", but cant make it work on my page. I get no results on my index.php, and the submit.php just shows "Array[]"
This is what I have so far:
Index.php holds the checkboxes and the jQuery script.
Checkboxes is in a drop down menu, like this:
<div id="menu">
<div id="mainmenu">Gender</div>
<div id="submenu1" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="male">Male</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="female">Female</a></div>
</div>
<div id="mainmenu">Price range</div>
<div id="submenu2" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="200">200-299$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="300">300-399$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="400">400-499$</a></div>
</div>
jQuery script:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
console.log(data);
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getSnowboardFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updateSnowboards(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#boards tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getSnowboardFilterOptions();
updateSnowboards(opts);
});
checkboxes.trigger("change");
</script>
At last I have submit.php, which holds the php code for selecting the right stuff.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
$opts = $_POST['filterOpts'];
$qMarks = str_repeat('?,', count($opts) - 1) . '?';
$statement = $pdo->prepare("SELECT gender, price_range, brand, model, rocker_type, flex, size_range, image FROM snowboards)");
$statement -> execute($opts);
$results = $statement -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Right now the SELECT query isn't specified, because I don't know how.
If someone knows what I'm doing wrong, or have better suggestion to solve it, please tell.

Categories