AngularJS Inserting and displaying from database - php

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.

Related

trouble using ajax to send form values to php file

I am trying to send the form values to another php file. After confirming to send the data, I will not receive the alert notification from the php file.
What i tried doing: I tried creating a test file with the shortened down version of the code, surprisingly that works
This is the first file.
<!DOCTYPE html>
<?php
include('../class/Appointment.php');
include('../main/databaseConnection.php');
$object = new Appointment;
if(!$object->is_Adminlogin()){
header("Location: ../main/error.php");
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doctor's Schedule</title>
<link rel="stylesheet" href="../css/add_schedule_popup.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="add_schedule_button" >Add Doctor Schedule</button>
<div id="add_schedule_popup" class="modal">
<div class="modal-content">
<div class="form-header">
<span class="close">×</span>
<h2>Add Doctor Schedule</h2>
</div>
<div class="form-body">
<form method="POST" action="" id="doctor_schedule_form">
<input type="hidden" name="action_type" id="action_type" value="add">
<div class="form-group">
<label>Select Doctor</label>
<select name="doctor_id" id="doctor_id" class="form-control" required>
<option value="">Select Doctor</option>
<?php
$object->query = "SELECT * FROM doctor_info ";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["doctor_id"].'">'.$row["doctor_firstname"].' '.$row["doctor_lastname"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Select Schedule Date</label>
<input type="date" name="schedule_date" id="schedule_date" required><br>
</div>
<div class="form-group">
<label>Select Timeslot</label>
<select name="schedule_timeslot" id="schedule_timeslot" class="form-control" required>
<option value="">Select Timeslot</option>
<?php
$object->query = "SELECT * FROM timeslot";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["schedule_timeslot"].'">'.$row["starting_time"].'-'.$row["ending_time"].' ('.$row["duration"].')</option>';
}
?>
</select>
</div>
<div>
<label>Select Availability</label>
<select name="schedule_status" id="schedule_status" class="form-control" required>
<option value="1">Available</option>
</select>
</div>
</div>
<br><br>
<div class="form-footer">
<button type="button" id="close_button">Close</button>
<input type="submit" id="submit_button" value="Confirm" name="submit_button">
</div>
</form>
</div>
</div>
<script>
var modal = document.getElementById("add_schedule_popup");
var btn = document.getElementById("add_schedule_button");
var span = document.getElementsByClassName("close")[0];
var close_button = document.getElementById("close_button");
btn.onclick = function() {
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
span.onclick = closeModal;
close_button.onclick = closeModal;
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
}
$(document).ready(function() {
$("#submit_button").click(function(){
e.preventDefault();
var doctor_id = $("#doctor_id").val();
var schedule_date = $("#schedule_date").val();
var schedule_timeslot = $("#schedule_timeslot").val();
var schedule_status = $("#schedule_status").val();
var action_type = $("#action_type").val();
console.log(doctor_id, schedule_date, schedule_timeslot, schedule_status, action_type);
$.ajax({
url: "modify_schedule_action.php",
type: "POST",
data: {doctor_id:doctor_id,schedule_date:schedule_date,schedule_timeslot:schedule_timeslot,schedule_status:schedule_status,action_type:action_type},
success: function(data) {
alert(data);
// Refresh the page or show a success message
},
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log(jqXHR.responseText);
}
});
});
});
</script>
</body>
</html>
And this is the php file that i am trying to send the values to
<?php
include('../class/Appointment.php');
$object = new Appointment;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'Received form data: ' . var_export($_POST, true);
}
if($_POST['action_type'] == 'add')
{
$data = array(
':schedule_date' => $_POST['schedule_date'],
':schedule_day' => date('l', strtotime($_POST["schedule_date"])),
':schedule_status' => $_POST['schedule_status'],
':schedule_timeslot' => $_POST['schedule_timeslot'],
':doctor_id' => $_POST['doctor_id'],
);
$object->query = "INSERT INTO `schedule` (`schedule_date`, `schedule_day`, `schedule_status`, `schedule_timeslot`, `doctor_id`)
VALUES (:schedule_date,:schedule_day,:schedule_status,:schedule_timeslot,:doctor_id)";
$object->execute($data);
$output = 'Data added successfully';
}
until now, the php file does not react to anything i do inthe first file. can anyone help me troubleshoot this error?
You have e.preventDefault(); in your event handler but e is not defined.
This will cause an error preventing your ajax code from running and your form will submit normally to itself as its action is blank.
$("#submit_button").click(function(e){// define the event parameter
e.preventDefault();

PHP OOP AJAX Form Submission Array Wont Append

I am trying to display the POST data of my form to the same page with Ajax. This is working fine but I am new to OOP and my class which builds an array with the POST content is getting overwritten on every request.
I understand I could post the data to a JSON file or Database but I wanted it to be solely displaying a "growing" array.
Index.php
<html>
<head>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,800" rel="stylesheet">
</head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
var frm = $('form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$("#response").html(data);
}
});
ev.preventDefault();
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="flex40">
<div class="container40">
<form id="form" action="response.php" method="post">
<input name="postName" type="text" placeholder="Name" required>
<select name="postEyeColour">
<option>Blue</option>
<option>Red</option>
<option>Yellow</option>
<option>Green</option>
</select>
<button name="submit" type="submit">New Person</button>
</form>
<div class="character-table">
<table id="response"></table>
</div>
</div>
</div>
</div>
</body>
</html>
response.php
<?php
require_once 'Classes/Person.php';
$character = new Person;
if (isset($_POST['postName'])) {
$character->createNewPerson();
$character->getPersonList();
}
?>
Classes/Person.php
<?php
class Person {
private $personList = array();
public function createNewPerson() {
// Build Array From Post Data
$newPerson= array(
"Name" => $_POST['postName'],
"Eye Colour" => $_POST['postEyeColour']
);
//Push New Person to data array
$this->personList[] = $newPerson;
}
public function getPersonList() {
print_r($this->personList);
}
}
?>
What happens is that the data is posted to the array but every time I add some more data it is resetting the Array with the new data not appending it.

how to update the data using angularjs+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";
});
}
});

Simple CRUD using AngularJS and PHP with JSON File for Storage

Before Down voting (I wanted to implement the CRUD using JSON file and not the Database)
I am using the below code in Angular JS to send the form data to PHP and from PHP I wanted to modify my local JSON file.
I am facing below issues
The Form values are going as Null in the JSON file
I want to append the array every time user clicks on the register button
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<form>
<h2>Register Form</h2>
<div>
<label>First Name</label>
<input type="text" ng-model="firstname" placeholder="First Name" required="required">
</div>
<div>
<label>Last Name</label>
<input type="text" ng-model="lastname" placeholder="Last Name" required="required">
</div>
<button ng-click='Register()'>Register</button>
</form>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="data in usersData">
<td>{{data.firstname}}</td>
<td>{{data.lastname}}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.Register = function () {
$http.post("misc.php", {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}).success(function (response) {
$scope.usersData = response.users;
});
};
});
</script>
</body>
</html>
PHP Code
<?php
$file="misc.json";
$json = json_decode(file_get_contents($file),TRUE);
$first = $_POST['firstname'];
$last = $_POST['lastname'];
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
But Once I Submit I am getting below info in the JSON file
{"":{"first":null,"last":null}}
But I wanted to send real values and the JSON format I want as
[{
"first": "John",
"last": "Anderson"
},
{
"first": "Mike",
"last": "Langer"
}]
I can answer for your 2nd question which is I want to append the array every time user clicks on the register button
Have a local array named $scope.usernames and when you are making a $http.post call inside that success function append it to the $scope.usernames array. Refer the code below.
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.usernames=[];
$scope.Register = function () {
$http.post("misc.php", {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}).success(function (response) {
$scope.usernames.push({"firstname":$scope.firstname,"lastname":$scope.lastname});
$scope.usersData = response.users;
});
};
});
I have used PHP long back so i couldn't find about the first error first make sure that it works in angular then make a post call

AngularJS pass form array to php

I am struggling to get this form to work was wondering if anyone can give me any ideas why! So what I have is an index page with an ng-app=especial. In the DIV main_area_holder goes the ng_view. The Ng-view displays fine and form displays on index page (from localtion app/partials/cust_form.php). What I am struggling to get working is the http request to php file so I can import form data into DB. I know the php code works without ajax (straight post request). If you can help out I would be very grateful.
app.js UPDATED
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
$scope = {};
$scope.custCreUpd = function(){
$http({
method: 'POST',
url: 'app/php/cust_cre_upd.php',
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log("OK", data)
}).error(function(err){"ERR", console.log(err)})
};
});
cust_cre_upd.php
<?php
$post = file_get_contents("php://input");
$values = json_decode($post, true);
$table='customers';
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
?>
index.php
<!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<link rel="stylesheet" href="css/index.css">
<script src="scripts/angular.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="scripts/angular-animate.js"></script>
</head>
<body>
<div class="header">
<img id="logo" src="images/especial-logo.jpg">
<a id="logout" href="logout.php">Logout</a>
<div class="menu"></div>
</div>
<div class="sub_menu"></div>
<div class="main_area">
<div id="main_area_holder" ng-view>
</div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>
cust_form.php
<div ng-controller="custPage">
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" name="cust[int_custID]" id="int_custID"/>
<label>Company:</label>
<input type="text" ng-model="cust.cust_company" name="cust[cust_company]" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 ng-model="cust.cust_address" name="cust[cust_address]" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" ng-model="cust.cust_postcode" name="cust[cust_postcode]" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" ng-model="cust.cust_contact_1" name="cust[cust_contact_1]" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" ng-model="cust.cust_contact_2" name="cust[cust_contact_2]" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" ng-model="cust.cust_tel" name="cust[cust_tel]" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" ng-model="cust.cust_mob" name="cust[cust_mob]" id="cust_mob"/>
<label>DDI:</label>
<input type="text" ng-model="cust.cust_DDI" name="cust[cust_DDI]" id="cust_DDI"/>
<label>Email:</label>
<input type="email" ng-model="cust.cust_email" name="cust[cust_email]" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes" name="cust[cust_notes]" id="cust_notes"></textarea>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
</div>
app.js:
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
$scope.cust = {};
$scope.custCreUpd = function(){
$http({
method: 'POST',
url: 'app/php/cust_cre_upd.php',
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(data)
}).error(function(err){
console.log(err)
})
};
});
cust_cre_upd.php
<?php
//print_r($_POST); you can print_r it for understanding
//use $_POST as usual, example $_POST["cust_ID"] means your
$values = $_POST;
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
index.php:
<!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<!-- <link rel="stylesheet" href="css/index.css">-->
<script src="scripts/angular-1.3.8.min.js"></script>
<script src="scripts/angular-route.min.js"></script>
<!-- <script src="scripts/angular-animate.js"></script>-->
</head>
<body>
<div class="header">
<img id="logo" src="images/especial-logo.jpg">
<a id="logout" href="logout.php">Logout</a>
<div class="menu"></div>
</div>
<div class="sub_menu"></div>
<div class="main_area">
<div id="main_area_holder" ng-view>
</div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>
cust_form.php (cust_form.tpl.html):
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" id="int_custID"/>
<label>Company:</label>
<input type="text" ng-model="cust.cust_company" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 ng-model="cust.cust_address" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" ng-model="cust.cust_postcode" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" ng-model="cust.cust_contact_1" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" ng-model="cust.cust_contact_2" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" ng-model="cust.cust_tel" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" ng-model="cust.cust_mob" id="cust_mob"/>
<label>DDI:</label>
<input type="text" ng-model="cust.cust_DDI" id="cust_DDI"/>
<label>Email:</label>
<input type="email" ng-model="cust.cust_email" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes" id="cust_notes"></textarea>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
I creat a repository here https://github.com/Danzeer/forJoshCrocker
To debug with script in web browser, you can use chrome's Developer's tools - network (option+command+i in OSX, F12 in window, and chose the network card).When you click submit, you can see request in network card and check http header by clicking the request.
I think you can find answer for "post" here AngularJs $http.post() does not send data
angualr's get works well, but angular's post does not seralize form-data as jquery.
my solution (maybe wrong, according to what I have searched) was rewriting angular's httpProvider:
app.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
2 your
ng-click="custCreUpd"
should be
ng-click="custCreUpd()"
3 check the result of below, I'm not familiar with it
$.param($scope.cust)
I have rewrite your code, that seems sending post. You can compare it with yours:
app.js :
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
//when using 1.3.8 version , consider how to write controller with []
especial.controller('custPage', ['$scope', '$http', function($scope, $http){
$scope.cust = {};
//$scope = {}; !!!!
$scope.custCreUpd = function(){ // pay attention of params
$http({
method: 'POST',
url: "app/php/cust_cre_upd.php",
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data){
console.log("OK", data)
}).error(function(err){"ERR", console.log(err)})
};
}]);
index.php:
!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<script src="js/angular-1.3.8.min.js"></script>
<script src="js/angular-route.min.js"></script>
<!-- <script src="scripts/angular-animate.js"></script>-->
</head>
<body>
<div id="main_area_holder" ng-view>
</div>
<script src="app/app.js"></script>
</body>
</html>
custForm.tpl.html(your cust_form.php):
<!--<div ng-controller="custPage"> !none ng-controller when using ng-route-->
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" name="cust[int_custID]" id="int_custID"/>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
naming custForm.tpl.html instead of cust_form.php seems much meaningful) and request of .php will be pass to php executor by apache/nginx while request for html only through apache/nginx. And pay attention to angular cache problem when using ng-route. -- some tools not relavent https://github.com/karlgoldstein/grunt-html2js and https://github.com/angular-ui/bootstrap, enjoy!
Points:
1 definition of controller
2 post of angularjs
3 how to use ng-view with ng-route
4 params-"$scope" of function custCreUpd hide $scope service

Categories