symfony Post data through Angularjs - angularjs

I'm trying to send ajax request with username and password through Angularjs to Symfony but the I can't access the post variables. Here is my code:
HTML:
<div>
<input type="text"
class="form-control defaultPassword"
ng-model="username"
placeholder="username">
</div>
<div class="form-group">
<input type="password"
ng-model="password"
class="form-control {% verbatim %}{{ passwordBox }}{% endverbatim %}"
placeholder="password">
</div>
<div>
<span>{% verbatim %}{{ message }}{% endverbatim %}</span>
<button id="submitBtn" class="btn" ng-click="login()">login</button>
</div>
AngularController
todoApp.controller("LoginController",
function LoginController($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = Login;
function Login(){
$http({
method: 'POST',
url: '/api/login',
data: {
username: $scope.username,
password: $scope.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
alert("error");
});;
}
});
And here is the symfony controller:
/**
* #Route("/api/login")
* #Method("POST")
*/
public function apiLogin(Request $request){
$us = $request->request->get("username");
}
This method of retrieving the data doesnt work. I can see that the username and password are being sent but i have no access to them. Can you help me to find another way to get them in the symfony controller?

Angular
$http({
method : 'POST',
url : url,
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
data : JSON.stringify(dataObj)
})
.success(function()
{
console.error("Done");
})
.error(function(dataObj)
{
console.error("Error");
});
Symfony
Include:
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
Function:
/**
* POST Route annotation.
* #Post("/api/login")
*/
public function apiLoginAction(Request $request)
{
$parameters = $request->request->all();

Related

how to send file and form data in angularjs to node.js server?

hello I am creating mean application for video upload form. I struck at one place when i do post request in angular js to my api then no data is going to my controller.Where am i doing wrong??
<form ng-submit="uploadComplete(form)" enctype="multipart/form-data" id="myForm" ng-controller = "addCtrl">
<div class="form-group">
<label >Title</label>
<input type="text" class="form-control" ng-model = "form.title" name="title" placeholder="Enter Title">
</div>
<div class="form-group">
<label >Description</label>
<textarea class="form-control" ng-model= "form.description" name ="description" rows="5" id="comment" placeholder="Enter Description"></textarea>
</div>
<div class="form-group">
<label >Author</label>
<input type="text" class="form-control" ng-model = "form.author" name ="author" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<div class="form-group">
<label >duration</label>
<input type="text" class="form-control" ng-model = "form.duration" name ="duration" id="exampleInputPassword1" placeholder="Enter duration Name">
</div>
<div class="form-group">
<label >ispublic</label>
<input type="text" class="form-control" ng-model = "form.public" name ="public" id="exampleInputPassword1" >
</div>
<input type="file" onchange="angular.element(this).scope().fileChanged(this)" id="userfile" name="userfile" multiple/>
<input type="submit" name="" value="submit">
my angular controller is
function addCtrl($scope, $filter, editableOptions,$http, editableThemes,$window,$uibModal, baProgressModal) {
$scope.fileChanged = function(elem){
$scope.files = elem.files;
$scope.$apply();
}
$scope.uploadComplete = function(f){
$http({
method: 'POST',
format: 'json',
url: '/api/add-video',
headers: {
'Content-Type': 'multipart/form-data'
},
data: JSON.stringify({
title: f.title,
description: f.description,
duration: f.duration,
author:f.author,
file:$scope.files,
ispublic:parseInt(f.public)
}),
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.then(function(success) {
console.log("hit " + JSON.stringify(success));
// $window.location.reload()
}, function(error) {
//console.log("not hit " + JSON.stringify(error));
});
}
console.log($scope.files[0].name);
console.log(parseInt(f.public));
}
}
})();
and my api/url which is part of server side
app.post('/api/add-video', addVideoHandler);
function addVideoHandler(req, res) {
var data = {
title: req.body.title,
description: req.body.description,
author: req.body.author,
duration: req.body.duration,
file: req.body.file,
ispublic: req.body.ispublic
}
console.log(data);
}
I already use all node package in above url file which i didn't mention.Why i didnt getting all data in console it displays :
{ title: undefined,
description: undefined,
author: undefined,
duration: undefined,
file: undefined,
ispublic: undefined }
Where am I doing wrong ??
Please guide me.Thankyou
Try to use a directive as below
.directive('fileModel', ['$parse', function($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.fileModel);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
}
}])
then replace input type=file to
<input type="file" class="form-control" id="fileId" accept="image/*" file-model="myFiles($files)"/>
and then in your controller add this
var formData = new FormData();
$scope.myFiles = function($files) {
formData.append('img', $files[0]);
}
Replace 'img' to a name which you want it as in backend
Add each and every values with keys in formData to send
as
formData.append('title', form.title);
formData.append('description', form.description);
formData.append('author', form.author);
formData.append('duration', form.duration);
formData.append('public', form.public);
and your $http method
$http({
method: 'POST',
url: '/api/add-video',
headers: {
'Content-Type': undefined
},
data: **formData**),
Node Side
then use multer diskStorage as to upload file to server
var uploadMulter = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./UploadDir");
},
filename: function(req, file, callback) {
callback(null, Date.now() + path.extname(file.originalname));
}
});
var upload = multer({ storage: uploadMulter });
./UploadDir is the destination folder where you want to upload your file
and finally your router
app.post('/api/add-video', upload.single('img'), addVideoHandler);
now if you want to upload a single file use upload.single('img')
** or for multiple use **upload.array('img',3) here 3 files will be uploaded. change as you want.
This is my first answer on StackOverflow :-)
if your destination dir UploadDir is not accessible try to join by
app.use('/UploadDir', express.static(path.join(__dirname, 'UploadDir')))
try this $http method if that dont work
$http.post('/api/add-video',formData,{headers:{'Content-Type': undefined}})
Change you Controller as
.controller('addCtrl', function($scope,$http){
var formData = new FormData();
$scope.myFiles = function($files) {
formData.append('img', $files[0]);
}
$scope.uploadComplete= function(form){
formData.append('title', form.title);
formData.append('description', form.description);
formData.append('author', form.author);
formData.append('duration', form.duration);
formData.append('public', form.public);
$http.post('/api/add-video',formData,{headers:{'Content-Type': undefined}}).then(function(res){
alert("Correctly Done")
}, function(err){
alert("Error check console in browser");
console.log(err)
})
}
})

IONIC APP- get device id for post service($http.post)

I'm trying to get the device id getUUID at the time of app login along with username and password. Is the right way to get device id and post it to the server for login.
controller.js
.controller('LoginCtrl', function($scope, $http,$rootScope,$window,$location,$cordovaDevice) {
$scope.login = function () {
var data ={
username : $scope.username,
password : $scope.password
};
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$http.post('login', data, config)
.success(function (data, status, headers, config) {
// $scope.DataResponse = data;
$location.path('#/tab/new-order');
})
.error(function (data, status, header, config) {
$window.alert("username or password incorrect");
});
console.log(device.cordova);
}
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
};
})
html code
<form action="" class="ki-login-form" method="post" accept-charset="utf-8">
<div class="form-group username">
<input type="text" class="form-control" name="username" value="" id="identity" placeholder="Your Name">
</div>
<div class="form-group pin">
<input type="text" class="form-control" name="password" value="" id="identity" placeholder="Your Pin">
</div>
<a type="submit" class="btns" ng-click='login()' >Login</a>
</form>
After login it has to be directed to a page href="#/tab/new-order" in the ionic tab
Add dependency injection $location in controller function like following -
.controller('LoginCtrl', function($scope, $http, $rootScope,$window,$location) {
// Your code
});
Solution for your added comment -
Use following -
Add device plugin : cordova plugin add org.apache.cordova.device
In your controller :
module.controller('MyCtrl', function($scope, $cordovaDevice) {
var uuid = $cordovaDevice.getUUID();
});
Change this
var data = $.param({
username : $scope.username,
password : $scope.password,
});
to
var data = {
username : $scope.username,
password : $scope.password,
};
UPDATE -
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}

The data alone is missing when I try to send from Angular.js to Node.js

I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}

how to send base64 images and textvalues as json object in angular js and spring mvc 4

I have converted my image to base 64 in angular js and send it to my controller but the controller does not get the image when decoded in the right format.The image in my angular js was 106kb but when i converted my image in base 64 the image size was only 8 bytes in controller
The html file
<html>
<head>
<script src="extensions/angular.min.js"></script>
<script src="bower_components/angular-base64/angular-base64.js"></script>
</head>
<body ng-app="myApp" ng-controller="testcontrol">
<input type="text" ng-model="A.username" placeholder="Enter Username" required>
<input type="password" ng-model="A.password" placeholder="Enter Password" required>
<input type="file" ng-model="B.img" placeholder="Browse image" required>
<input type="button" value="Send" ng-click="setValues()" />
<input type="button" value="Send" ng-click="getValues()" />
<script>
var app = angular.module('myApp', ['base64']);
app.controller('testcontrol', function($scope, $http,$base64) {
$scope.setValues = function() {
alert("post");
var a=$base64.encode($scope.B);
$scope.A.image=a;
console.log(a);
$http({
method : 'POST',
url : 'form/post',
headers : {
'Content-Type' : 'application/json'
},
data : $scope.A
}).success(function(data) {
alert(JSON.stringify(data));
});
};
$scope.getValues = function() {
alert("get");
$http.get('form/get').then(
function(response) {
if (response) {
alert(JSON.stringify(response));
}
});
};
});
</script>
</body>
</html>
The Controller in spring
#Controller
#RequestMapping(value="/form")
public class Form {
#ResponseBody
#RequestMapping(value="/post" ,method=RequestMethod.POST)
public String save(#RequestBody TestDto test)
{
logger.info("username"+test.getUsername());
logger.info("password"+test.getPassword());
logger.info("image"+test.getImage());
byte[] decodedValue = Base64.getDecoder().decode(test.getImage());
try {
FileOutputStream f=new FileOutputStream(new File("/home/shalom/Pictures/tets.png"));
f.write(decodedValue);
f.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe it works if you override the default request transformer in your post request:
$http({
method : 'POST',
url : 'form/post',
headers : {
'Content-Type' : 'application/json'
},
transformRequest : [function (data, headers) {
//just send data without modifying
return data;
}],
data : $scope.A
}).success(function(data) {
By default angular tries to dectect if the request's data contains JSON and modifies the data.
For more information see angular $http api docs section "Transforming Requests and Responses"

angularjs (http post) with python and google app engine

Rookie question.
I am trying to create a contact form with angularjs and python backend on google app engine. The form so far does send the email, however the Subject and Body fields are not captured in the email. Can someone tell what I am doing wrong?
HTML:
<body ng-app="submitExample">
<form ng-submit="submit()" ng-controller="ExampleController">
<div>
<p>Name</p>
<input ng-model="name" name="name" id="name" rows="1" cols="20"/>
</div>
<div>
<p>Email</p>
<input ng-model="email" name="email" id="email" rows="1" cols="20"/>
</div>
<div><p></p><input type="submit" value="Send Email"></div>
</form>
</body>
angularjs:
angular.module('submitExample',[]).controller('ExampleController', function($scope,$http){
$scope.formData;
$scope.submit = function() {
$http({
method: "post",
url: "/sign",
data: {
name: $scope.name,
email: $scope.email
}
})
}
});
Python:
class SendEmail(webapp2.RequestHandler):
def post(self):
from_address = cgi.escape(self.request.get('email'))
to_address = "test#gmail.com"
subject = cgi.escape(self.request.get('name'))
body = "xxx"
mail.send_mail(from_address, to_address, subject, body)
I found the answer.
Instead of this angularjs code:
angular.module('submitExample',[]).controller('ExampleController', function($scope,$http){
$scope.formData;
$scope.submit = function() {
$http({
method: "post",
url: "/sign",
data: {
name: $scope.name,
email: $scope.email
}
})
}
});
Use this one:
angular.module('submitExample', []).controller('ExampleController', function($scope,$http,$httpParamSerializerJQLike) {
$scope.formData;
$scope.submit = function() {
$http({
method: "post",
url: "/sign",
data: $httpParamSerializerJQLike({
name: $scope.name,
email: $scope.email
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
Works like a charm.

Resources