Angular JS contact form - javascript

I'm trying to come to grips with created an angularjs Contact form. Below is a link of what I have created thus far. Click Here I fill I am on the write track with the code i have written
var app = angular.module("myApp", []);
app.controller("contactCtrl", function ($scope) {
$scope.success = false;
$scope.error = false;
$scope.send = function () {
var htmlBody ='<div>Name: ' + $scope.user.name + '</div>' +
'<div>Email: ' + $scope.user.email + '</div>' +
'<div>Message: ' + $scope.user.body + '</div>' +
'<div>Date: ' + (new Date()).toString() + '</div>';
$http({
url: 'https://api.postmarkapp.com/email',
method: 'POST',
data: {
'From': 'foo#foo.com',
'To': 'me#gmail.com',
'HtmlBody': htmlBody,
'Subject': 'New Contact Form Submission'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '8569dcd45-6a1a-4e7b-ae75-ea37629de4'
}
}).
success(function (data) {
$scope.success = true;
$scope.user = {};
}).
error(function (data) {
$scope.error = true;
});
}
});
However I am receiving two errors
And also
{"error": "Please use POST request"}
Does anyone know how I can solve this issues, I've wasted too many hours trying to get my head around it?

You don't declare the $http. It should be:
app.controller("contactCtrl", ['$scope','$http',function ($scope,$http){
// your code
}]);

Related

Angular display a single record from json

I've just started getting into using Angular and having an issue displaying a single record that is being returned from using $http (get). I'm getting the data back correctly. This is the html I've got....
<div ng-controller="UserDataController as udCtrl">
Name: {{udCtrl.user.name}}
</div>
<div id="debug" style="margin-top:24px;border:solid 1px #900;background:#efefef;min-height:100px"></div>
have also tried and a couple of other variations...
Name: {{udCtrl.name}}
Javascript:
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var user=this;
user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
This is what is returned in JSON format and I can see this in the little debug area I created.
{"data":{"id":"1","name":"Joe Bloggs"}
if I change the html to use the code below it works.
<div ng-controller="UserTest as udCtrl">
Name: {{udCtrl.user.name}}
</div>
I just cannot see where I'm going wrong and why it will not display the returned name.
Define the user variable on $scope and access it with $scope.user. You are having referance problem.
Example
//Define user variable like this.
$scope.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
$scope.user=response.data;
}
}
EDIT
If you want to use udCtrl referance define variable under thisvariable on controller.
//Define user variable like this.
var ctrl = this;
ctrl.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
ctrl.user=response.data;
}
}
EDIT 2 FOR ABSOLUTE ANSWER
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var udCtrl=this;
udCtrl.user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
udCtrl.user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();

AngularJS + API call

Trying to understand how AngularJS works, doing my first API calls, when I got stuck.
I want to do 2 API calls, but I can't seem to make it work.
After the first $http.get I want to do an another call (using the information from the previous call) but that doesn't work for some reason. (I get no alert)
The city and country are working perfectly after the first .get
JS:
var app = angular.module('weather', []);
app.controller("weatherCtrl", function($scope, $http) {
$http.get("http://ipinfo.io/json").then(function(response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
var apiKey = "";
var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + response.data.city + "&APPID=" + apiKey;
$http.get(apiCall).then(function(responsew) {
// $scope.temperature would get a value here
alert("1")
});
});
})
HTML:
<body ng-app="weather" ng-controller="weatherCtrl">
<h1 class="text-center">Weather</h1>
<h2 class="text-center">{{city}}, {{country}}</h2>
<h2 class="text-center">{{temperature}} °C</h2>
</body>
You can use promise to call the request after another which is the recommended way to do,
Another thing is you are missing the http part in the second request
Code:
app.controller("weatherCtrl", function ($scope, $http) {
function infoReq() {
return $http({
method: 'Get',
url: 'http://ipinfo.io/json'
})
}
function weatherReq() {
var apiKey = "";
var apiCall = "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
return $http({
method: 'Get',
url: apiCall,
})
}
$scope.makeRequest = function () {
infoReq()
.then(function (response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
return weatherReq();
})
.then(function (response) {
console.log(response.data);
})
}
})
var req = {
method: 'POST',
url: "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
You can use the above http service to make the request inside your angularjs controller.

Using Angular XEditable inside UI-Router Partial

Can't get my form to work inside UI-Router, it works outside of the partial but not inside. XEditable is not "loading" it's like it's out of scope.
I tried to lazy load it using ocLazyLoadProvider but couldn't get that to work either.
Please help!
my code:
Main view:
doctype html
html(lang="en")
include ../includes/head
body.backoffice
div.container
include ../includes/navbar
.page-body(ng-app='geckoAdminApp')
include includes/nav
div(ui-view='maincontent')
//include includes/management
div.padding
include ../includes/foot
Partial View:
//-
//- Buildings Form
//-
div(ng-controller='BuildingsController')
h2 Edificios
table.table.table-bordered.table-hover.table-condensed.table-striped
thead.thead-default
tr
th
strong Nome
th
strong Descrição
th
strong Total de Espaços
th
strong Total de Boxes
th
tr(ng-repeat='building in buildingsData')
td
a( ng-click='setCurrentBuildingID(building.idBuilding, building.shortName)' ng-show='toggleShortname' href='') {{ building.shortName }}
span( ng-hide='toggleShortname' editable-text='building.shortName' e-name='shortName' e-form='buildingrowform') {{ building.shortName }}
td
span(editable-text='building.description' e-name='description' e-form='buildingrowform') {{ building.description }}
td
span(editable-number='building.nSpaces' e-name='nSpaces' e-form='buildingrowform') {{ building.nSpaces }}
td
span(editable-number='building.nBoxes' e-name='nBoxes' e-form='buildingrowform') {{ building.nBoxes }}
td(style='white-space: nowrap')
// form
form(editable-form myForm name='buildingrowform' onbeforesave='saveBuildingData($data, building.idBuilding)' ng-show='buildingrowform.$visible' class='form-buttons form-inline' shown='inserted == building')
button.glyphicon.glyphicon-save.glyphButton.btn-to-glyph.glyphButtonOk(type='submit' title='Salvar' ng-disabled='buildingrowform.$waiting')
a(href='' ng-disabled='buildingrowform.$waiting' ng-click='buildingrowform.$cancel()' title='Cancelar')
span.glyphicon.glyphicon-remove-circle.glyphButton.glyphButtonAlert(aria-hidden='true')
div.buttons(ng-show='!buildingrowform.$visible')
a(href='' ng-click='buildingrowform.$show(); toggleShortnameFunction()' title="Editar")
span.glyphicon.glyphicon-edit.glyphButton(aria-hidden='true')
a(href='' ng-click='removeBuilding(building.idBuilding, $index)' title="Remover")
span.glyphicon.glyphicon-remove.glyphButton.glyphButtonAlert(aria-hidden='true')
a(href='' ng-click='addBuildingRow()' title="Adicionar")
span.glyphicon.glyphicon-plus.glyphButton.glyphButtonOk(aria-hidden='true')
Angular:
angular.module('geckoAdminApp', ['xeditable', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('edificios', {
url: '/edificios',
views: {
'maincontent': { templateUrl: '/partials/admin/partial-buildings.html' }
},
controller: 'BuildingsController'//,
});
})
.controller('BuildingsController', ['$scope', '$filter', '$http', '$window', function ($scope, $filter, $http, $window) {
// $ocLazyLoad.load('xeditable');
$scope.buildingsData = [];
$scope.regex = /[A-Z]{1}\d{2}$/;
$scope.currentBuildingID = '';
$scope.setCurrentBuildingID = function (id, shortName) {
console.log('>> ID: ' + id);
$scope.currentBuildingID = id;
$window.location.href = '/admin/edificio/' + shortName;
};
$scope.toggleShortnameFunction = function () {
$scope.toggleShortname = !$scope.toggleShortname;
};
$scope.GetBuildings = function () {
$http.get(GeckoBuildingUrl).then(function (res) {// jshint ignore:line
$scope.buildingsData = res.data.item; //TODO: Verificar status code
console.log(res.data);
}, function (res) {
console.log('ERROR: Can\'t get buildings: ' + res.data);
$scope.buildingsData = [];
});
};
$scope.GetBuildings();
$scope.saveBuildingData = function (building, buildingId) {
if (buildingId) {
$scope.toggleShortnameFunction();
console.log('Update Building: ' + building.shortName + ' ' + building.description + ' ' + building.nSpaces + ' ' + building.nBoxes + ' ');
$http({
url: GeckoBuildingUrl + '/' + buildingId,// jshint ignore:line
//url: building.URI,
method: 'PUT',
contentType: 'application/x-www-form-urlencoded',
data: {
shortName: building.shortName,
description: building.description,
nSpaces: String(building.nSpaces),
nBoxes: String(building.nBoxes)
}
}).then(function successCallback() {
$scope.GetBuildings();
}, function errorCallback(response) {
console.log(response);
});
} else {
console.log('New Building: ' + building.shortName + ' ' + building.description + ' ' + building.nSpaces + ' ' + building.nBoxes + ' ');
$http({
url: GeckoBuildingUrl,// jshint ignore:line
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: {
shortName: building.shortName,
description: building.description,
nSpaces: String(building.nSpaces),
nBoxes: String(building.nBoxes)
}
}).then(function successCallback(response) {
$scope.GetBuildings();
console.log('success post:' + response);
}, function errorCallback(response) {
console.log(response);
});
}
};
$scope.removeBuilding = function (buildingId, index) {
if (buildingId) {
console.log(GeckoBuildingUrl + '/' + buildingId);// jshint ignore:line
$http({
url: GeckoBuildingUrl + '/' + buildingId,// jshint ignore:line
method: 'DELETE',
contentType: 'form-data',
data: {}
}).then(function successCallback(response) {
$scope.GetBuildings();
console.log('success DELETE:' + response);
}, function errorCallback(response) {
console.log('error DELETE:' + response);
});
}
$scope.buildingsData.splice(index);
};
$scope.addBuildingRow = function () {
$scope.inserted = {
shortName: '',
description: '',
nSpaces: 0,
nBoxes: 0
};
$scope.buildingsData.push($scope.inserted);
};
}]);
Thanks!

angularJS interceptor: access parent controller method

In my app i have different manipulations with http request's, for example:
$scope.getArticle = function(id) {
$http.get('/app/' + id, {
headers: {
'Content-Type': 'application/json',
}
})
.success(function(response) {
})
.error(function(data, status, headers, config) {
});
};
$scope.displayAlert = function (message) {
var modalHtml = '<div class="modal-header"><h3>Warning</h3></div>';
modalHtml += '<div class="modal-body"><strong>' + message + '</strong></div>';
modalHtml += '<div class="modal-footer"><button class="btn-md btn-green pull-right" ng-click="$dismiss()">OK</button></div>';
$scope.modalInstance = $modal.open({
template: modalHtml,
size: 'sm',
backdrop: 'static',
keyboard: false
});
$timeout(function () {
$scope.modalInstance.close('closing');
}, 5000);
};
and i have written such interceptor:
var responseError = function (rejection) {
var rootScope = rootScope || $injector.get('$rootScope');
console.log(rootScope.displayAlert('123'));
***
return $q.reject(rejection);
};
but how could i in this interceptor when i have error call $scope.displayAlert() method?
sure i could do it so:
$scope.getArticle = function(id) {
$http.get('/app/' + id, {
headers: {
'Content-Type': 'application/json',
}
})
.success(function(response) {
})
.error(function(data, status, headers, config) {
$scope.displayAlert('error');
});
};
but this is bad idea... how to be?
You can use the $rootScope along with $broadcast and $on as an event bus to communicate between components. Note that this may have performance impact, so you should take care when employing these methods.
in your service:
var responseError = function (rejection) {
var rootScope = rootScope || $injector.get('$rootScope');
....
$rootScope.$broadcast('responseError',{
message: 'Rejection Reason' });
and in the controller:
$scope.$on('responseError', function(event, data){
$scope.displayAlert(data.message); });

Angular Contact form email submission issue

I have created a contact Click here for example i believe i have created all the credentials needed for this form, however when i sent the message to the email credentials highlighted in my code, i don't an email submission from the sender. Does anyone know how this problem can be solved ?
angular
.module('hfApp')
.controller('contactCtrl', ['$scope','$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;
$scope.send = function () {
var htmlBody ='<div>Name: ' + $scope.user.name + '</div>' +
'<div>Email: ' + $scope.user.email + '</div>' +
'<div>Message: ' + $scope.user.body + '</div>' +
'<div>Date: ' + (new Date()).toString() + '</div>';
$http({
url: 'http://www.hfpersonaltrainer.com/',
method: 'POST',
data: {
'From': 'foo#foo.com',
'To': 'nate.tyrone#gmail.com',
'HtmlBody': htmlBody,
'Subject': 'New Contact Form Submission'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': '8569dcd45-6a1a-4e7b-ae75-ea37629de4'
}
}).
success(function (data) {
$scope.success = true;
$scope.user = {};
}).
error(function (data) {
$scope.error = true;
});
};
}])

Categories

Resources