submit form data to serverside - javascript

<form ng-submit="doRegister()">
<div class="control-group">
<label for="email">E-Mail Address</label>
<input type="email" id="email" name="email" ng-model="user.email" autofocus>
</div>
<div class="control-group">
<label for="password">Password</label>
<input type="password" id="password" name="user.password" ng-model="password">
</div>
<div class="control-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" id="password_confirmation" name="password_confirmation" ng-model="user.password_confirmation">
</div>
<input type="submit">
</form>
How do I submit the form to register via POST? Technically I don't know where data could be placed.
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.doRegister = function(){
$http.post('/register', data).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
angular.element('.errors').html(data.errors.join('<br>')).slideDown();
});
};
}
EDIT: Progress:
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.user = {};
$scope.doRegister = function(){
$http.post('/register', $scope.user);
};
}
but the request sent to the server was an empty array in php:
Array()

You already have a properties binded within the form.
You can define data using them.
For example, for email field:
var data = {};
data.email = $scope.email;
Or you can even define $scope.data = {} in controller,
and post it.
EDIT on 9/14
This seems to be one of the problem that people see with $http.post() for sending
form data. Solution is given in the following Q&A.
AngularJS - Any way for $http.post to send request parameters instead of JSON?

You need to declare variables and change headers like this:
function registerCtrl ($scope, $http) {
document.title = 'Register';
$scope.user = {
email: '',
password: ''
};
$scope.doRegister = function(){
$http({
url: '/register',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
});
};
}
And you need

AngularJS' post method sends data as Request Payload.
Just use:
$json = json_decode(file_get_contents("php://input"));
You can access values in php by using
$email = $json->email;
$password = $json->password;
$password_confirmation = $json->password_confirmation;

<form id="Register" action="/register">
<div class="control-group">
<label for="email">E-Mail Address</label>
<input type="email" id="email" name="email" ng-model="email" autofocus>
</div>
<div class="control-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" ng-model="password">
</div>
<div class="control-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" id="password_confirmation" name="password_confirmation" ng-model="password_confirmation">
</div>
<input type="submit">
</form>
call ajax function.
$.ajax({
url: form.prop('action'),
type: 'POST',
data: form.serialize(),
dataType: 'json',
async: false,
success: function (result) {
}
}); // ajax post end
var form = $("#Register");
data pass form.serialize() that is very easy to pass data from server side.

Related

PHP is not returning data to AJAX

I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>
try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem

Angularjs with rails API rest post 400 (bad request)

Hello i making a project of rails api and angularJs,And I found the following error.
angular.js:11821 POST http://localhost:3000/people 400 (Bad Request)
And I could not find why.
code below.
Rails Controller
# POST /people
def create
#person = Person.new(person_params)
if #person.save
render json: #person, status: :created, location: #person
else
render json: #person.errors, status: :unprocessable_entity
end
end
AngularJS
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('http://localhost:3000/people', data, config)
.then(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.catch(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
Html
<div ng-app="myApp" ng-controller="person">
<div class="modal-body">
<div class="form-group">
<label for="exampleInputEmail1">Name:</label>
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">age:</label>
<input type="text" class="form-control" name="age" ng-model="age" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">gender:</label>
<input type="text" class="form-control" name="gender" ng-model="gender" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">lonlat:</label>
<input type="text" class="form-control" name="lonlat" ng-model="lonlat" placeholder="Email">
</div>
<button ng-click="SendData()"
class="btn btn-default">Submit</button>
{{ PostDataResponse }}
thanks for listening
I cannot see your person_params definition, but if it is like when produced by rails generators, you are missing to wrap your params in a person hash
var data = $.param({person:
{ name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat }
});

Form Not Clearing after submit POST AngularJS

I'm using angularjs frontend and Play framework backend to process posted data.
The challenge i'm facing is that the form is not resetting after successful posting of data I click submit.
My View is as below and is as below.
<form name="signupForm" ng-submit="signup()" novalidate>
<div>
<label for="email">Email</label>
<input name="email" class="form-control" type="email" id="email" placeholder="Email"
ng-model="email">
</div>
<div>
<label for="password">Password</label>
<input name="password" class="form-control" type="password" id="password"
placeholder="Password" ng-model="password">
</div>
<button type="submit" class="btn btn-primary">Sign up!</button>
</form>
My Angular controller is as below
angular.module('clientApp')
.controller('SignupCtrl', function ($scope, $http, $log) {
$scope.signup = function() {
var payload = {
email : $scope.email,
password : $scope.password
};
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
});
};
});
I'm using chrome browser. How do i get to clear the email and password fields after clicking submit?
Set the $scope.email and $scope.password to null like
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
$scope.email = null;
$scope.password = null;
$scope.signupForm.$setPristine(); //Set form to pristine mode
});

angularjs JavaScript inheritance, fail to bind data from view to a controller

what am trying to do is to get data from the form use it in my controller in HTTP post call but it's not working
I know i might have problem with inheritance of scopes but icant solve it.
here is my controller code:
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.submit = function() {
var url = 'http://localhost:3000/register';
var user = {
email: $scope.email,
password: $scope.password,
};
console.log($scope.user);
$http.post(url, user)
.success(function(res){
console.log('You are now Registered');
//$state.go('app.items');
})
.error(function(err){
console.log('Could not register');
// $state.go('error');
});
};
})
Here is the code of my Template:
<form name="register">
<div class="list">
<label class="item item-input no-border">
<input name="fullname" type="text" ng-model="fullname" placeholder="Full Name" required="">
</label>
<label class="item item-input">
<input name="email" type="email" ng-model="user.email" placeholder="Email" required="">
</label>
<p class="blue-font" ng-show="register.email.$dirty && register.email.$invalid">Please Write valid Email.</p>
<label class="item item-input">
<input name="password" type="password" ng-model="user.password" placeholder="Password" required="">
</label>
<button ng-click="submit();" ng-disabled="register.$invalid" type="submit" class="button signup-btn sharb-border white-font blue-bg-alt border-blue-alt ">
Sign Up
</button>
</div>
</form>
Note: i tried the ng-submit its not really the problem
Inside the controller.
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.user = {
email: '',
password: ''
};
$scope.submit = function() {
And this
var user = {
email: $scope.user.email,
password: $scope.user.password
};
Also drop the ; in ng-click
<button ng-click="submit()" ...>
Try to use rootScope (docs.angularjs.org/$rootScope").

AngularJS $scope data is not showing any thing

The submitform() does not take the for datas to the function. Chrome console says ReferenceError: $ is not defined. Is there anything wrong in the code ?
var app = angular.module('app', []);
app.controller('testimonialController', function($scope, $http) {
$scope.formdata = {};
$scope.submission = false;
$scope.submitform = function($scope, $http) {
$http({
method: 'POST',
url: 'sendmail.php',
data: $.param($scope.formdata), // pass in data as strings
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).
success(function() {
console.log("send successfuly");
}).
error(function() {
console.log("It is failed");
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="contact-form" ng-controller="testimonialController" ng-app="app">
<h1 id="contact">Contact</h1>
<pre>Form data: {{formdata}}</pre>
<p>Take a look around the site, Do you have something in mind you would like to let me know .You can contact me by filling the form below or email hello#athimannil.com</p>
<form ng-submit="submitform()">
<div class="form-wrap">
<label for="name">Name</label>
<input type="text" name="name" ng-model="formdata.name" placeholder="Name" required>
<br>
</div>
<div class="form-wrap">
<label for="email">Email</label>
<input type="email" name="email" ng-model="formdata.email" placeholder="Email" required>
<br>
</div>
<div class="form-wrap">
<label for="comment">Message</label>
<br>
<textarea name="comment" id="comment" ng-model="formdata.comment" placeholder="Comment" cols="30" rows="10" required></textarea>
<br>
</div>
<input type="submit" name="submit" value="Send">
</form>
</div>
This is the console message when use
$http({
method : 'POST',
url : 'sendmail.php',
data : $scope.formdata, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).
data: $.param($scope.formdata)
This line uses jQuery's $.param method. You have to include it, if you want to use it

Categories