angularjs (http post) with python and google app engine - angularjs

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.

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);
}

Angular form submiting twice

I have a form, it sends data to a database, but it makes it twice.
Here is the code of controller and example of html view.
$scope.addEvent = function(type) {
if (!$scope.sentAdd) {
$scope.newEvent.admission = type;
$scope.newEvent.customer_id = $scope.curUID;
console.log($scope.newEvent);
$http({
url: '/addEvent',
method: "POST",
data: $.param($scope.newEvent),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.success(function(data){
//console.log(data);
$scope.newEvent = $scope.cleanEvent;
$scope.addEventForm.$setPristine();
$scope.sentType = type;
$scope.sentAdd = true;
$.fancybox.close();
$.fancybox.open({ href: '#eventSuccess', type: 'inline' });
});
}
};
<form name="addEventForm" novalidate>
<input type="text" ng-model="text">
<a ng-click="addEvent('Paid')">Add Paid Event</a><br>
<a ng-click="addEvent('Free')">Add Free Event</a>
</form>

symfony Post data through 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();

Angularjs calling restful api (post) without success bad request

I have to call a restful API with basic auth "i think the auth is working)"
that needs this special custom header: "X-AppGlu-Environment: staging" I don't know how to put the header" then I need to post to one URL, data with this format:
Body:
{
"params": {
"stopName": "what you want search"
}
}
Let's see my code at moment "it's not structured yet"
controller:
'use strict';
angular.module('myApp', ['base64'])
.controller('transportController', function($scope, $http, $base64){
$scope.$watch('search', function() {
fetch();
});
function fetch(){
var data = {
"params": {
"stopName": $scope.search
}
}
$http.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
var encoded = $base64.encode("xxxx:xxxx");
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post("the url", data)
.then(function(response){ $scope.details = response.data; });
}
});
view:
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" onclick="select()" class="form-control" placeholder="Enter destiny" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
I receive a error 400 bad request when i try to search for something, i think is something with the format of the object i'm trying to send, but if is, i don't know what to change.
Is working now i changed to this structure
function fetch(){
var data = {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
var encoded = $base64.encode("xxxx:xxxx");
$http({
url: "url",
headers : {
"X-AppGlu-Environment":"staging",
"Authorization": "Basic "+encoded,
"Content-Type" : "application/json; charset=utf-8"
},
method: 'POST',
data: {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
}).then(function(response){
$scope.details = response.data.rows;
});
// $http.get("http://www.omdbapi.com/?s=" + $scope.search)
//.then(function(response){ $scope.related = response.data; });
}

Resources