AngularJS pass form array to php - 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

Related

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.

Inserting comment to database using ajax

I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});

Jquery php mysql login does send data to mysql but doesn't return right value?

Question: I can see that the data is getting written to the database but $action doesn't become register in the insert.php call from the html file and hence php JSON return is NULL ??
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
You should use Chrome Dev Tools or Firebug in Firefox to inspect the response from the AJAX call. You set the call to expect JSON as the data type and you also use it as JSON. The problem is you have this line:
echo "1 record added";
Which is output before your JSON. So your response probably looks something like:
1 record added{"status": false, "message": "No Login"}
This isn't valid JSON and it will not parse, and thusly this line will never work:
if(result.status) {

using ajax to display a message when data get inserted in to the data base

I've searched through the StackOverFlow but didn't found what I was looking for so I'm posting what I want to ask you.
I'm a new comer to the world of PHP any how I've started to write a script which will get data and display on a WAP interface that part is ok my issue is in the part I'm writing for the data insert page or the Admin page. I've got every thing working but I love to know how to use AJAX to display a message with out going to the particular processing page.
The Process Page,
<?php
include ('connect.php');
$data = ("SELECT * FROM poiinfo");
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
/*$poiImg = $_REQUEST['Image']; */
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
?>
Can I know how to use AJAX to get an message.
I've used the code examples that you guys gave me but I'm still not getting the job done please can you help me to find what I'm doing wrong.
My Form,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name");
var desc = document.getElementById("Descrip");
var con = document.getElementById("ConInfo");
var dataString = 'Name='+name'&Descrip='+desc'&ConInfo='con;
$.ajax({
type:'POST',
data:dataString,
url:'addpoipro.php',
success:function(data){
if(data="Data inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image :</label>
<!--<input type="file" name="Image" id="Image" /> -->
</p>
<p> </p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Above4 is my form and the process.php is before that please help me thank you.
Example using jQuery's $.ajax:
$.ajax({
url: "process.php",
type: "POST",
data : { Name : 'John', Descrip : 'some description..', ConInfo : 'some info...' },
success : function(data){
if(data == "Data inserted")
{
console.log("Success!");
}
else
{
console.log("fail!");
}
}
});
Here is another solution without using jquery.
index.html
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<!-- reply from process.php is shown in this div -->
<div id=message></div>
<!-- click to send data -->
click here
</body>
</html>
test.js
function sendData(Name,description,info) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
var ajaxDisplay = document.getElementById('message');
if(ajaxRequest.readyState == 4)
{ ajaxDisplay.innerHTML = ajaxRequest.responseText;}
else { document.getElementById('message').innerHTML="<span style=\"color:green;\">Loading..</span>"; }
}
var url="process.php?name="+Name+"&Descrip="+description+"&ConInfo="+info;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
You can do it like this also.
You HTML
<label>Name</labe><input type="text" id="name" name="full_name" value="" />
<label>Address</labe><input type="text" id="addr" name="addr" value="" />
<input type="button" name="save" id="save_data" value="Save" />
in the head section after adding jQuery do something like this
<script>
$(document).ready(function(){
$("#save_data").click(function(){
var name = $("#name").val();
var addr = $("#addr").val();
var dataString = 'name='+name'&address='+address;
$.ajax({
type:'POST',
data:dataString,
url:'process.php',
success:function(data){
if(data="inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
"process.php page"
$name = $_POST['name'];
$address = $_POST['address'];
// DO YOUR INSERT QUERY
$insert_query = mysql_query("INSERT QUERY GOES HERE");
if(// CHECK FOR AFFECTED ROWS) {
echo "inserted";
} else {
echo "not";
}

PHP for parsing JSON and adding to database mysql

I am making a web app (android) with phonegap and jquery mobile.
I am trying to send three fields from an html form as json, to a php page which will decode the json string/object (im new to json, ajax, jquery) and add the three fields as a mysql query to a database on my localhost.
My html page looks like this:
<script type="text/javascript">
$(document).ready(function(){
$('#btn').bind('click', addvalues);
});
function addvalues(){
$.ajax({
url: "connection.php",
type: "POST",
data: "id=" + $("#id").val()+"&name=" + $("#name").val() + "&Address=" + $("#Address").val(),
datatype:"json",
success: function(status)
{
if(status.success == false)
{
//alert a failure message
}
else {
//alert a success message
}
}
});
}
</script>
</head>
<body>
<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<input type="submit" id "btn" value="Add record" data-icon="star" data-theme="e">
</form>
</div>
</body>
The Question is:
How exactly do i extract the three fields (ID, name, Address) from the string that i have sent to my php file (connection.php)?
connection.php is hosted by my local server.
I am familiar with making connections to database, as also with adding queries to mysql. I only need help with extracting the three fields, as i am new to ajax and jquery and json.
As of now, this is ALL i have done in connection.php:
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
//I do not know how to use the json_decode function here
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
Please add the relevant code in this file and help me out.
I will be highly obliged.
:)
what you want to do this this
$(document).ready(function () {
$('#btn').on('click', function () {
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
} else {
//alert a success message
}
}
});
});
});
then in your php do this
//set variables from json data
$data = json_decode($_POST); // Or extract(json_decode($_POST) then use $id without having to set it below.
$id = $data['id'];
$name = $data['name'];
$Address = $data['Address'];
//And this is how, i suppose, we will add the values to my table 'sample'
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
be sure you sanitize those inputs before you insert them though.
use:
$id = json_decode($_POST['id']);
$name = json_decode($_POST['name']);
$Address = json_decode($_POST['Address']);
$sql .= "VALUES ($id, '$name', '$Address')";
in place of :
$sql .= "VALUES ($id, '$name', '$Address')";
use $id_json_encoded = json_encode($_POST['id']);
to encode the posts of the form
then use jquery script like this
<script type="text/javascript">
$(document).ready(function()
{
$("#audit").click(function(){
$.post("/audit_report/"+$('#branch').val()+"/"+$('#ttype').val()+"/"+$('#from').val()+"/"+$('#to').val(),
{
targetDiv:"divswitcher"
}
,
function(data){
$("#imagediv").html('<img src="/public/images/spinner_white.gif"> loading...');
//alert(data);
$("#bodydata").html(data);
$("#imagediv").html('');
// $("#divswitcher").html(data);
});
});
});
this is the complete code that encodes form data and send it to the server using ajax
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#btn").click(function(){
var encoded = json_encode("/audit_report/"+$('#id').val()+"/"+$('#name').val()+"/"+$('#Address').val());
$.post(encoded,
{
targetDiv:"divswitcher"
}
,
function(data){
$("#imagediv").html('<img src="spinner_white.gif"> loading...');
//alert(data);
$("#bodydata").html(data);
$("#imagediv").html('');
// $("#divswitcher").html(data);
});
});
});
</script>
</head>
<body>
<div data-role="header">
<h1>My header text</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" name="id" >
</label>
<label for="name">
<input type="text" id="name" name="name" >
</label>
<label for="Address">
<input type="text" id="Address" name="Address" >
</label>
<input type="button" id="btn" name="btn" value="Add record" />
</form>
</div>
</body>
</html>
<div id="bodydata" class="class">
</div>

Categories