Email Form Post to PHP with AngularJS - javascript

I have been building Ionic Mobile app with AngularJS. and im trying to send email form. PHP part is working fine. i tested it with parametered URL and it worked. but with the application its not working.
here my HTML part
<form>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Name" ng-model="name">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="email">
</label>
<label class="item item-input">
<textarea row="10" cols="50" placeholder="Message" ng-model="message"></textarea>
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="feedbacksubmit();">Submit</button>
</label>
</div>
</form>
and Here my ControllerJS part
$scope.feedbacksubmit= function (){
$scope.buttonclick() // to Check button has click (yes button works)
$http.post("http://boost.meximas.com/mobile/email.php?name="+name+"&email="+email+"&message="+message).success(function(data){
//$scope.tasks = data;
$scope.donemessage();
});
};
Here my PHP code
<?php
$name=$_GET['name'];
$email=$_GET['email'];
$message=$_GET['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("testing#gmail.com", $subject, $message, $from);
echo "Email sent!";
}
?>

Try to post the data as a JSON object and pass it as the second argument for $http.post().
var data = {
name: 'foo bar',
email: 'foo#bar.com'
};
$http.post("http://boost.meximas.com/mobile/email.php", data)
.success(function(data){
//$scope.tasks = data;
$scope.donemessage();
});

Sample Code and JsFiddle: http://jsfiddle.net/YGQT9/
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {
firstname: "default",
emailaddress: "default",
gender: "default",
member: false,
file_profile: "default",
file_avatar: "default"
};
$scope.submitForm = function() {
console.log("posting data....");
$http.post('http://posttestserver.com/post.php?dir=jsfiddle', JSON.stringify(data)).success(function(){/*success callback*/});
};
});

Related

Using Angular to post to a APi

First week using Angular and I am now trying to post to a third party API.
I would like some help getting this form posting the data correctly, for extra points some comments and expectation on what line is doing what.
I am getting this error
ReferenceError: formData is not defined
at h.$scope.processForm (controller.js:116)
at angular.js:10567
at angular.js:18627
at h.$eval (angular.js:12412)
at h.$apply (angular.js:12510)
at HTMLFormElement.<anonymous> (angular.js:18626)
at angular.js:2780
at q (angular.js:330)
at HTMLFormElement.c (angular.js:2779)
The API I am posting to requires user_key 0000 and api_key 0000to be sent, although theses are not dynamic like the form fields so are always the same.
My current form
<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2" ng-click="postdata(Fname, Lname, email)">
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button ui-sref="form.select" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
</div>
</form>
My controller
// submit button controller POST
// =============================================================================
.controller('formController', function ($scope, $http) {
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
$scope.processForm = function (Fname, Lname, email) {
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,
api_key: 0000,
user_key: 0000
};
//Call the services
$http.post('https://API/do/create', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function (response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
You should have some changes in your code.
1- Declare $scope.formData = {}
2- Remove
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
because you can access to them with $scope.formData object.
3- change formData.Fname to $scope.formData.Fname, and other similar to this
$scope.formData = {}; // declare in controller
var data = {
Fname: $scope.formData.Fname,
Lname: $scope.formData.Lname,
email: $scope.formData.email,
api_key: 0000,
user_key: 0000
};
4- you can pass formData object to function or don't pass it.If passing formData to function so use following
ng-click="postdata(formData)"
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,

jQuery script not writing values in database Mysql

My database has a table called utilizatori and has id,username,nume_prenume,parola,locatie,sambata columns.
Through the form, I am trying to add new entries in database but when I submit the form, it doesn`t add any entry.
A demo can be found HERE.
The update and delete operations are working fine.
HTML form:
<script src="js/jQuery/jquery.min.js"></script>
<!-- Include AngularJS library -->
<script src="lib/angular/angular.min.js"></script>
<!-- Include Bootstrap Javascript -->
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal alert alert-warning" name="empList" id="empForm" ng-submit="insertInfo(empInfo);" hidden>
<h3 class="text-center">Insert Employee Details Into Database</h3>
<div class="form-group">
<label for="Username">Nume utilizator:</label>
<input type="text" name="username" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.username" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.username.$invalid && empList.username.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Nume_prenume">Nume angajat:</label>
<input type="text" name="nume_prenume" class="form-control" placeholder="Enter Employee Email Address" ng-model="empInfo.nume_prenume" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.nume_prenume.$invalid && empList.nume_prenume.$dirty">Invalid Email!</p>
</div>
<div class="form-group">
<label for="Parola">Parola cont:</label>
<input type="text" name="parola" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.parola" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.parola.$invalid && empList.parola.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Rol_user">Rol:</label>
<input type="text" name="rol_user" class="form-control" placeholder="Enter Employee Address" ng-model="empInfo.rol_user" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.rol_user.$invalid && empList.rol_user.$dirty">Address field is Empty!</p>
</div>
<div class="form-group">
<button class="btn btn-warning" ng-disabled="empList.$invalid">Add Into Database</button>
</div>
</form>
<script src="js/angular-script.js"></script>
Angular JS script:
// Application module
var crudApp = angular.module('crudApp', []);
crudApp.controller("DbController", ['$scope', '$http', function($scope, $http) {
// Function to get employee details from the database
getInfo();
function getInfo() {
// Sending request to EmpDetails.php files
$http.post('databaseFiles/empDetails.php').success(function(data) {
// Stored the returned data into scope
$scope.details = data;
});
}
// Setting default value of gender
$scope.empInfo = {
'rol_user': 'Operator receptie'
};
// Enabling show_form variable to enable Add employee button
$scope.show_form = true;
// Function to add toggle behaviour to form
$scope.formToggle = function() {
$("#empForm").slideToggle();
$("#editForm").css('display', 'none');
}
$scope.insertInfo = function(info) {
$http.post('databaseFiles/insertDetails.php', {
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
if (data == true) {
getInfo();
$("#empForm").css('display', 'none');
}
});
}
$scope.deleteInfo = function(info) {
$http.post('databaseFiles/deleteDetails.php', {
"del_id": info.id
}).success(function(data) {
if (data == true) {
getInfo();
}
});
}
$scope.currentUser = {};
$scope.editInfo = function(info) {
$scope.currentUser = info;
$('#empForm').slideUp();
$('#editForm').slideToggle();
}
$scope.UpdateInfo = function(info) {
$http.post('databaseFiles/updateDetails.php', {
"id": info.id,
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
$scope.show_form = true;
if (data == true) {
getInfo();
}
});
}
$scope.updateMsg = function(emp_id) {
$('#editForm').css('display', 'none');
}
}]);
Insert info PHP script:
<?php
// Including database connections
require_once 'database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from submitting data & storing in new variables.
$username = mysqli_real_escape_string($con, $data->username);
$nume_prenume = mysqli_real_escape_string($con, $data->nume_prenume);
$parola = mysqli_real_escape_string($con, $data->parola);
$rol_user = mysqli_real_escape_string($con, $data->rol_user);
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";
// Inserting data into database
mysqli_query($con, $query);
echo true;
?>
And database_connections.php script:
<?php
$con = mysqli_connect("localhost", "user", "pasword", "database");
?>
I found the issue. I was trying to write in 4 columns, but there are 6 (excluding id which is auto increment.
If I rewrite this query to write in all 6 or I remove the other 2 columns from database, will work.
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";

Getting "405 Not Allowed" after doing an Ajax post request for same domain

I would expect this to happen for CORS but I'm literally attempting something in the same domain and I'm at a loss.
I simple html form:
<form action="" method="post" class="wpcf7-form contact-form">
<div class="contact-input-fields">
<p>
<span class="wpcf7-form-control-wrap">
<label for="name">Name*</label>
<input type="text" id="name" name="name" value="" class="wpcf7-form-control" required="">
</span>
</p>
<p>
<span class="wpcf7-form-control-wrap">
<label for="email">Email*</label>
<input type="email" id="email" name="email" value="" class="wpcf7-form-control" required="">
</span>
</p>
<p>
<span class="wpcf7-form-control-wrap">
<label for="subject">Subject*</label>
<input type="text" id="subject" name="subject" value="" class="wpcf7-form-control" required="">
</span>
</p>
</div><!-- /.contact-input-fields -->
<p>
<span class="wpcf7-form-control-wrap">
<label for="message">Message*</label>
<textarea id="message" name="message" class="wpcf7-form-control" required=""></textarea>
</span>
</p>
<p class="choose-table-form">
<input type="submit" id="submit" value="Enviar" class="wpcf7-form-control wpcf7-submit" style="max-width:100%;">
</p>
</form><!-- /.contact-form -->
This is my javascript:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".success").hide();
$("#submit").click(function() {
var data = {
name: $("#name").val(),
email: $("#email").val(),
subject: $("#subject").val(),
message: $("#message").val()
};
$.ajax({
url: "forms/contactForm.php",
type: "POST",
data: data,
success: function(data){
$(".success").fadeIn(1000);
}
});
});
});
</script>
and my PHP:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$msg = "Name: ".$name."\nEmail: ".$email."\Subject: ".$subject."\nMessage: ".$message;
//send email
mail("email#domain.com", "Message" .$email, $msg);
}
I don't see anything wrong but everytime I press "submit" and trigger the ajax call I get the "405 Not Allowed".
I've looked around at other answers here but they're mostly CORS related.
I don't see any div with success class on it, so you need to add that to your HTML, I used bootstrap so it uses alert-success
<div class="alert-success">Done!</div>
And in your jQuery code, use preventDefault(); and the full url to the php file
$(".alert-success").hide();
$("#submit").click(function(e) {
e.preventDefault();
var data = {
name: $("#name").val(),
email: $("#email").val(),
subject: $("#subject").val(),
message: $("#message").val()
};
$.ajax({
url: "http://localhost/jquery/forms/contactForm.php",
type: "POST",
data: data,
success: function(data){
$(".alert-success").fadeIn(1000);
}
});
});
Also, make sure you are testing this within a server, whether localhost using wamp or xampp or on a live server.

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

After Angularjs validation is true do a normal form submit

I am implementing AngularJS on an existing web application that requires a common HTTP POST like you would do without AngularJS.
Does any one have a work around to do that?
i have tried setting action="#" and action="." and just action and then do some jquery to inject a action like this. but nothing works
<script type="text/javascript">
$("form").get(0).setAttribute( "action", "test.html" );
</script>
HERE IS MY FORM AND CODE
//MY FORM
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="form-group">
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="userFormData.fornavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Fornavn" required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.efternavn.$invalid && !userForm.efternavn.$pristine }">
<label class=" control-label" for="textinput">Efternavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('efternavn'); ?>" name="efternavn" ng-model="userFormData.efternavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Efternavn" required>
</div>
</div>
<button id="membership-box__payBtn" type="submit" ng-model="userFormData.betaling" name="betaling" class="btn btn-success text-uppercase">Gå til betaling</button>
</form>
//CODEIGNITER CONTROLLER
if (isset($_POST['betaling'])) {
$data['tilBetaling'] = array(
'oprettelse' => $this->input->post('oprettelse'),
// 'medlemskab' => $this->input->post('medlemskab'),
'tilBetaling' => str_replace(',', '.', $this->input->post('tilBetaling')),
'pr_maaned' => $this->input->post('pr_maaned'),
'start_date' => $this->input->post('start_date'),
'til_dato' => $this->input->post('til_dato'),
'pakke' => $this->input->post('pakke'),
'type' => $this->input->post('medlemskabTypeFinal'),
'getCenter' => $this->input->post('getCenter'),
'medlemskabPakkePID'=> $this->input->post('medlemskabPakkePID'),
'ekstraInput' => $this->input->post('ekstraInput'),
'periode_price' => $this->input->post('periode_price'),
'kampagneTag' => $this->input->post('kampagneTag'),
// 'header' => $this->input->post('header'),
);
//Gem array til session
$_SESSION['betaling'] = $data['tilBetaling'];
}
If you want to do a normal submit, you can handle ngClick in your controller:
HTML
<div ng-controller="ctrl">
<form name="userForm" action="user/add" method="post">
Name: <input name="name" ng-model="user.name" />
...
<button ng-click="onSubmit(userForm)">Submit</button>
</form>
</div>
JS
app.controller('ctrl', function($scope) {
$scope.onSubmit = function(form) {
if (form.$valid) {
var e = document.getElementsByName(form.$name);
e[0].submit();
}
}
});
An Alternative Solution
As an alternative, consider leveraging services, and redirecting after a successful POST in AngularJS.
HTML
<div ng-controller="ctrl">
<form name="userForm" ng-submit="onSubmit(user)">
Name: <input name="name" ng-model="user.name" />
...
<button type="submit">Submit</button>
</form>
</div>
JS
app.factory('UserService', function($http) {
return {
addUser: function(user) {
return $http({method:'POST', url:'api/user/add', data: user });
}
}
});
app.controller('ctrl', function($scope, $location, UserService) {
$scope.onSubmit = function(user) {
if ($scope.userForm.$valid) {
UserService.addUser(user).success(function() {
$location.path('/user/addSuccessful')
});
}
}
});
Even if you do an AngularJs submit, the request does not go to server. The control still remains on client side. Then you can post the data/form etc through $http service. You can inject $http service in your controller. as
app.controller('reviewCtrl', ['$http', function($http){
$scope.addReview = function(product){
//use $http service here
// Simple POST request example (passing data) :
$http.post(' / someUrl ', {msg:' hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
note: please review the syntax before running the code.
To submit the Angular Js form ONLY after Angular validations are through or passed, you must use reviewForm.$valid flag chack in ng-submit.
With this flag check, the form will not get submitted until all validations are passed.
<form name="reviewForm" ng-controller="reviewCtrl" ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate>
....
....
</form>

Categories

Resources