I am trying to gain some experience with creating an Ionic app. In my app, I have created a registration form.
register.html
<form ua-signup ng-controller="registerCtrl">
<ion-view title="Sign Up">
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<span class="input-label">ID</span>
<input type="text" ng-model="data.id">
</label>
<label class="item item-input">
<span class="input-label">First Name</span>
<input type="text" ng-model="data.fname">
</label>
<label class="item item-input">
<span class="input-label">Last Name</span>
<input type="text" ng-model="data.lname">
</label>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" ng-model="data.email" ua-is-email>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="data.pass">
</label>
<label class="item item-input">
<span class="input-label">Mobile No.</span>
<input type="tel" ng-model="data.tel">
</label>
<label class="item item-input item-select">
<div class="input-label" ng-model="data.course">
Course
</div>
<select>
<option selected>HUBIT</option>
<option>HUBMC</option>
<option>HUBIM</option>
<option>HUBGM</option>
</select>
</label>
<label class="item item-input">
<div class="input-label">
Subject
</div>
<select multiple="multiple">
<option selected>HUBIT</option>
<option>HUBMC</option>
<option>HUBIM</option>
<option>HUBGM</option>
</select>
</label>
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive" ng-click="Register(data);">
<span ng-show="!loading">Create Account</span>
<i ng-show="loading" class="ion-loading-b"></i>
</button>
</div>
</ion-content>
</ion-view>
<div class="bar bar-footer bar-assertive" ng-show="error">
</div>
</form>
controller.js
app.controller('registerCtrl', function($scope,$http,$state) {
$scope.user = {};
$scope.register = function(data){
$scope.id = $scope.data.id;
$scope.fname = $scope.data.fname;
$scope.lname = $scope.data.lname;
$scope.email = $scope.data.email;
$scope.pass = $scope.data.pass;
$scope.tel = $scope.data.tel;
$scope.course = $scope.data.course;
$http.post("http://localhost:81/fyp/register.php",{
'id':$scope.id,
'fname':$scope.fname,
'lname':$scope.lname,
'email':$scope.email,
'pass':$scope.pass,
'tel':$scope.tel,
'course':$scope.course
})
.success(function(data, status, headers, config){
console.log("data inserted");
})
$state.go('tab.dash');
}
});
And my register.php which is on a xampp server
?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$id = mysql_real_escape_string($request->id);
$fname = mysql_real_escape_string($request->fname);
$lname = mysql_real_escape_string($request->lname);
$password = mysql_real_escape_string($request->pass);
$email = mysql_real_escape_string($request->email);
$phone = mysql_real_escape_string($request->tel);
$course = mysql_real_escape_string($request->course);
// Connect to MySQL
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Could not connect to database </body></html>");
};
// open a9963146_fyp16 database
$db_select = mysql_select_db('fyp',$db);
if (!$db_select) {
die("Could not connect to database </body></html>");
};
if($id != '' && $lname != '' & $password != '' && $email != '' && $phone != ''){
$query = mysql_query("INSERT into Student(id, firstname, lastname, password, email, phone, course) values ('$id', '$fname', '$lname', '$password', '$email', '$phone', '$course')");
echo "Registered successfully!";
}
else{
echo "All fields must be filled!";
}
mysql_close( $db );
?>
I am still new to this and I am practicing. But I found out that the value I am trying to insert, is not added to my database. Why is it so? Did I do something wrong with codes in controller.js and the register.php? Can someone show me the mistakes I made and how can I correct it?
I would recommend you start by changing the $http.post to the following:
var body = {
'id':$scope.id,
'fname':$scope.fname,
'lname':$scope.lname,
'email':$scope.email,
'pass':$scope.pass,
'tel':$scope.tel,
'course':$scope.course
};
$http.post("http://localhost:81/fyp/register.php", body)
.then(function(response) {
console.log(response);
}, function(error) {
console.log(error);
}
The reason being that the .success method has been deprecated for this function, as described here:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
This will probably not solve your problem, but the added error function should allow you to see whether there are any errors, which you can then share with us so we can help you further. The added variable for the body is completelyoptional.
Related
I am trying to send data from my ionic app to mysql. The problem is when I click on the submit button, it actually post empty records in the database.
My HTML code
<form >
<label class="item item-input">
<span class="input-label">Product Name:</span>
<input type="text" ng-model="productname">
</label>
<label class="item item-input">
<span class="input-label">Product Price:</span>
<input type="number" ng-model="productprice" >
</label>
<label class="item item-input">
<span class="input-label" >Description:</span>
<input type="text" ng-model="productdescription">
</label>
<input type="button" value="Submit" class="button button-assertive button-block" ng-click="submit()">
</form>
The controller for the project
App.controller('appCtrl', ['$scope', '$http', '$state, function ($scope,
$http, $state, $ionicPopup, $timeout) {
$scope.submit = function (){
var link = "http://localhost/api.php";
$http.post(link, {
'productname' : $scope.productname,
'productprice' : $scope.productprice,
'productdescription' : $scopeproduct.description,
}).success(function(response){
$scope.pdata= response;
console.log(response);
//console.log(response);
})
}
}]);
This is my PHP code to post the the data to database
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "ionic");
if ($conn->connect_error) {
die("Connection failed: " .$conn->connect_error);
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata);
$pname = $request->productname;
$pprice = $request->productprice;
$pdescription = $request->productdescription;
$sql = ("INSERT INTO `users` ( product_name, product_price, description) VALUES ('$pname', '$pprice', '$pdescription')");
mysqli_query($conn, $sql);
}
?
Well, I am trying to insert data from an Ionic form to an MySQL database using a PHP server, i've followed this tutorial.
But when I try to insert data on the database it doesn't work.
Here's the code:
insertProdutos.html
<ion-view title="Products" id="page4" class=" " ng-controller="DataCtrl">
<ion-content padding="true" class="has-header">
<form id="form-promocao" class="list " ng-submit="submit()">
<p id="" style="margin-top:3px;color:#44729C;text-align:center;" class=" ">Entre com as informações do produto</p>
<ion-list id="cadastro-promocao" class=" ">
<label class="item item-input " id="codigoDoProduto">
<input type="number" placeholder="Codigo de barras..." ng-model="data.codigo">
</label>
<label class="item item-input " id="nomeDoProduto">
<input type="text" placeholder="Nome do produto..."ng-model="data.nome_produto">
</label>
<label class="item item-input " id="tipo_comercializacao">
<input type="text" placeholder="Tipo de comercializacao..."ng-model="data.tipo_comercializacao">
</label>
<label class="item item-input " id="Medida">
<input type="number" placeholder="Medida..." ng-model="data.medida">
</label>
<label class="item item-input " id="Peso">
<input type="number" placeholder="Peso..." ng-model="data.peso">
</label>
<input class="button button-block button-positive"
type="submit" name="submit" value="Submit to server" >
</ion-list>
</form>
</ion-content>
</ion-view>
controllers.js
.controller('DataCtrl', function($scope, $http) {
$scope.data = {};
$scope.submit = function(){
var link="http://localhost/PHPserver/api.php"
$http.post(link, {id_produto: $scope.data.codigo, nome_produto: $scope.data.nome_produto, medida_produto: $scope.data.medida, peso_produto: $scope.data.peso, tipo_comercializacao: $scope.data.tipo_comercializacao}).then(function (res){
$scope.response = res.data;
});
};
});
api.php
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
include("connect.php");
$request = json_decode($postdata);
$codigo = $request->codigo;
$produto = $request->nome_produto;
$medida = $request->medida;
$tipoComercializacao= $request->tipo_comercializacao;
$peso = $request->peso;
$sql="INSERT INTO produto(id_produto, nome_produto,peso,tipo_comercializacao,valor_medida) VALUES('".$codigo."','".$produto."','".$peso."','".$tipoComercializacao."','".$medida."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
When I insert the data on the form and press "Submit to server", nothing happens, it doesn't submit and I get no erros on console log.
I would appreciate some help here.
Thank you :)
I have created angularjs form. I want to store the form values into data base using PHP and before inserting I want to check weather the email is already exists or not. I am new to PHP. Any help would be appreciated. Thanks.
Register.html:
<div class="container col-lg-10" style="margin-top:2em; margin-left:2em;" >
<div class="panel panel-default">
<div class="panel-body" ng-app="TempleWebApp" ng-controller="RegisterCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (userForm.name.$dirty || submitted)}">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Your Name" ng-required="true">
<p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitted)" class="help-block">You name is required.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && (userForm.email.$dirty || submitted)}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Your Email Address" ng-required="true">
<p ng-show="userForm.email.$error.required && (userForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && (userForm.password.$dirty || submitted)}">
<label>Password</label>
<input type="Password" name="password" class="form-control" ng-model="user.passwrd" placeholder="Your Password" ng-required="true">
<p ng-show="userForm.password.$error.required && (userForm.password.$dirty || submitted)" class="help-block">Your password is required.</p>
</div>
<!-- TERMS & CONDITIONS -->
<div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid && (userForm.terms.$dirty || submitted)}">
<label>Accept Terms & Conditions</label>
<input type="checkbox" value="" name="terms" ng-model="user.terms" ng-required="true" />
<p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || submitted)" class="help-block">Accept terms & conditions.</p>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Register</button>-->
<button type="submit" class="btn btn-primary col-lg-offset-6">Register</button>
</form>
<pre>{{user}}
</pre>
</div>
</div>
</div>
Main.js:
var app = angular.module('TempleWebApp', [ 'ngRoute']);
app.controller('RegisterCtrl', function ($scope,$location, $http) {
$scope.user = {};
$scope.user.name= "" ;
$scope.user.email ="";
$scope.user.passwrd="";
$scope.user.terms="";
// function to submit the form after all validation has occurred
$scope.submitForm = function () {
// Set the 'submitted' flag to true
$scope.submitted = true;
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
console.log("Inserted Successfully!");
});
};
});
PHP code.
<?php
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$con = mysql_connect("localhost","root","");
mysql_select_db("userregister");
$sql = "insert into user(username,email,password) values($username,'$email','$password')";
$result = mysql_query($sql);
?>
Try using mysqli in the following manner (Also note you should create the variable $dbname and assign the right dbname to it:
$data = json_decode(file_get_contents("php://input"));
$username = #$data->username;
$email = #$data->email;
$password = #$data->password;
$dbname = '';
$conn = new mysqli("localhost","root","",$dbname);
$check = "SELECT * FROM user WHERE email='$email'";
//The following rows check whether this email already exists in the DB
$results = $conn->query($check);
if($results && mysqli_num_rows($results)>0)
{
echo "email";
die;
}
//The following rows will work only if there is no such email in the DB
if($conn->connect_error)
{
echo "false";
die;
}
$sql = "INSERT INTO user VALUES values($username,'$email','$password')";
if ($conn->query($sql) === true)
{
echo "true";
}
You will also need to change your Javascript to fit the possible events:
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
if(data == 'true'){
console.log("Inserted Successfully!");
}
else if(data == 'email'){
console.log("The email already exists");
}
else{
console.log("There was an issue connecting to the DB");
}
});
I'm using AngularJs and PHP to try and accomplish this but it doesn't seem to work.
I have created a virtual host with WAMP and inside the folder from which I'm receiving all my content I have created an uploads folder to which I would like to store files I have uploaded via different forms. The problem is that whenever I execute my PHP the folder is still empty. Here is the code I use:
AngularJs
myApp.controller('AdminPromotionsDetailsController', function($scope, $http) {
$scope.msg = '';
$scope.msg_type = 'error';
$scope.savePromotion = function(promotion) {
$scope.promotion.PromotionPhoto = promotion.PromotionPhoto.name;
$http.post('save.php', promotion)
.success(function(data, status, headers, config) {
if (data == 'success') {
$scope.msg = 'Success message';
$scope.msg_type = 'success';
} else {
$scope.msg = 'Error message';
$scope.msg_type = 'error';
}
}).error(function(data, status) {
$scope.msg = 'Error message';
$scope.msg_type = 'error';
});
}
});
PHP
<?php
$con = mysqli_connect('ecommerce', 'root', '', 'my_db');
// Check connection
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con,"utf8");
$data = json_decode(file_get_contents("php://input"));
$id = '';
if(!empty($data->PromotionId)) {
$id = mysqli_real_escape_string($con, $data->PromotionId);
}
$name = mysqli_real_escape_string($con, $data->PromotionName);
$link = mysqli_real_escape_string($con, $data->PromotionLink);
$cover = mysqli_real_escape_string($con, $data->PromotionPhoto);
$date_start = mysqli_real_escape_string($con, $data->PromotionDateStart);
$date_end = mysqli_real_escape_string($con, $data->PromotionDateEnd);
$folder = 'http://ecommerce/uploads/';
move_uploaded_file($cover, "$folder".$cover);
if(!empty($data->PromotionContent)) {
$content = mysqli_real_escape_string($con, $data->PromotionContent);
} else {
$content = '';
}
if ($id != '') {
$sql = "UPDATE `promotions` SET PromotionName='$name', PromotionLink='$link', PromotionPhoto='$cover', PromotionDateStart='$date_start', PromotionDateEnd='$date_end', PromotionContent='$content' WHERE `PromotionId`='$id'";
$sql_res = mysqli_query($con, $sql) or die(mysqli_error($con));
if ($sql_res) {
print 'success';
} else {
print 'error';
}
} else {
$sql = "INSERT INTO promotions (PromotionName, PromotionLink, PromotionPhoto, PromotionDateStart, PromotionDateEnd, PromotionContent) VALUES ('$name', '$link', '$cover', '$date_start', '$date_end', '$content')";
$sql_res = mysqli_query($con, $sql) or die(mysqli_error($con));
if ($sql_res) {
print 'success';
} else {
print 'error';
}
}
?>
HTML
<form autocomplete="off" name="promotionForm">
<input type="hidden" value="" ng-model="promotion.PromotionId" />
<div class="form-notification form-notification--{{msg_type}}" ng-if="msg != ''">
{{msg}}
</div>
<div class="form-notification form-notification--error" ng-if="promotionForm.file.$error.maxSize">
{{msg}}
</div>
<ul>
<li class="input">
<label for="promotion_name" class="input__label">
Title
</label>
<input type="text" class="input__field" value="" ng-model="promotion.PromotionName" id="promotion_name" required="required" />
</li>
<li class="input">
<label for="promotion_link" class="input__label">
URL
</label>
<input type="text" class="input__field" value="" ng-model="promotion.PromotionLink" id="promotion_link" required="required" />
</li>
<li class="input">
<label for="promotion_link" class="input__label">
Cover
</label>
<input type="file" ngf-select ng-model="promotion.PromotionPhoto" name="file"
accept="image/*" ngf-max-size="10MB" required id="promotion_link"
class="input__field input__field--upload"
ngf-model-invalid="errorFile"
/>
<img ng-show="promotionForm.file.$valid" ngf-thumbnail="promotion.PromotionPhoto" alt="" />
<button ng-click="promotion.PromotionPhoto = null" ng-show="promotion.PromotionPhoto">
Remove
</button>
</li>
<li class="input">
<label for="date_start" class="input__label">
Date
</label>
<ul class="row">
<li class="small-6 columns">
<datepicker ng-model='promotion.PromotionDateStart' date-format='MMMM d, yyyy' disable-timepicker='true' ng-patter='/\d\d/\d\d/\d\d\d\d/' required></datepicker>
</li>
<li class="small-6 columns">
<datepicker ng-model='promotion.PromotionDateEnd' date-format='MMMM d, yyyy' disable-timepicker='true' ng-patter='/\d\d/\d\d/\d\d\d\d/' required></datepicker>
</li>
</ul>
</li>
<li class="input">
<label for="promotion_content" class="input__label">
Content
</label>
<text-angular ng-model="promotion.PromotionContent"></text-angular>
</li>
</ul>
<button type="submit" class="button--big" ng-click="savePromotion(promotion)"
ng-if="promotion.PromotionId != null"
>
Edit
</button>
<button type="submit" class="button--big" ng-click="savePromotion(promotion)"
ng-if="promotion.PromotionId == null"
>
Add
</button>
</form>
I found the answer I had to set the $folder to $_SERVER['DOCUMENT_ROOT'].'/uploads/'
You cannot POST files in JSON. While you use ng-file-upload, you can use the service Upload for your uploads. It takes care of headers and give you the ability to track your progress. Check https://github.com/danialfarid/ng-file-upload#usage
I am not able to connect to the database what should be the syntax when I have created the database (myDb) using phpMyAdmin. I have placed signup.php on the server i.e www folder.
Please point out if there is some other mistake I have made in this code.
signup.html:
<ion-header-bar class="bar-positive">
<h2 class="title">SignUp</h2>
</ion-header-bar>
<ion-view view-title="SignUp" name="signup-view">
<ion-content class="has-header">
<div class="list list-inset">
<label class="item item-input item-floating-label">
<span class="input-label">Enter Username</span>
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Enter Your Email</span>
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Enter Your Password</span>
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-calm" ng-click="signUp(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
signup.php:
<?php
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysql_connect("localhost","root",'') or die ("Failed to connect to MySQL: " . mysql_error());;
mysql_select_db('myDb', $con);
$qry_em = 'select count(*) as cnt from users where email="' . $email . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,password,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
app.js:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function () {
var request = $http({
method: "post",
url: "http://localhost/signup.php",
crossDomain : true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.userdata.username,
email: $scope.userdata.email,
password: $scope.userdata.password
},
});
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Account Created Successfully!";
}
if(data == "2"){
$scope.responseMessage = "Can not Create Account";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exists"
}
});
}
});
use $request->email, $request->password, $request->username instead of $postdata->email, $postdata->password, etc...
If PHP is must, I would recommend looking at Slim Framework which is made for creating APIs.Some other solutions that fits here (probably better than PHP & MySQL for this purpose) are Mongo + Express or ParseSDK for JavaScript are something to look at as well. I would recommend Parse since it is very easy to get started with and remove a lot of back end headaches.
Sample example using ionic to access API:
Controller:
app.controller('AppCtrl', function($scope){
$http.get('API_URL')
.then(
function(data){
console.log(data);
$scope.data = data;
// JSON data returned as response
},
function(err){
console.log(err);
$scope.err = err;
// when error occurs
}
);
});
View:
<ion-content ng-controller="AppCtrl">
<div> {{ data }} {{ err }} </div>
</ion-content>
Example of usage of JSON data.