Angular Contact form email submission issue - javascript

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

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

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!

Http request configuration url must be a string. Received: undefined

I just moved my upload function from controller (where it was working as it should) to factory and it sudenly stopped working. I'm keep getting this error, but i don't know/understand where the problem is
angular.js:13550 Error: [$http:badreq] Http request configuration url must be a string. Received: undefined
http://errors.angularjs.org/1.5.5/$http/badreq?p0=undefined
at angular.js:68
at $http (angular.js:11194)
at uploadWithAngular (ng-file-upload.js:91)
at sendHttp (ng-file-upload.js:144)
at upload (ng-file-upload.js:330)
at Scope.$scope.uploadDocument (locationsCtrl.js:131)
at fn (eval at compile (angular.js:14432), <anonymous>:4:338)
at expensiveCheckFn (angular.js:15485)
at callback (angular.js:25018)
at Scope.$eval (angular.js:17229)
This is my upload document function in controller
$scope.uploadDocument = function(file) {
if($scope.documentName.length > 4) {
$scope.errorMsg = '';
file.upload = Upload.upload( documentsFactory.uploadDocument(
$scope.id_location,
$scope.documentName,
$scope.documentDescription,
file,
$scope.locationUniqueId
));
file.upload.then(function (response) {
$scope.documentName = $scope.documentDescription = $scope.userFile = '';
documentsFactory.getDocuments($scope.id_location).then(function (data) {
$scope.documents = data;
});
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}else{
$scope.errorMsg = 'Name should be at least 5 chars long';
}
};
And this is my factory
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return $http({
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
}).then(function successCallback(response){
return response.data;
},function errorCallback(response){
console.log('Error uploading documents: ' + response);
});
};
UPDATE:
This is working example if i make "upload request" in my controller
file.upload = Upload.upload({
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents/',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: $scope.id_location,
name: $scope.documentName,
description: $scope.documentDescription,
userFile: file,
locationUniqueId: $scope.locationUniqueId
}
});
If you need any additional inflammations please let me know and i will provide. Thank you in advance
Following the error stack:
From ng-file-upload repository.
this.upload = function (config, internal) {
which is called by you there
Upload.upload( documentsFactory.uploadDocument(
$scope.id_location,
$scope.documentName,
$scope.documentDescription,
file,
$scope.locationUniqueId
));
line 330
return sendHttp(config);
line 144
uploadWithAngular();
line 91
$http(config).then(function (r) {
Where the error gets thrown. It looks like Upload.upload doesn't accept a promise, but a config for the $http call.
EDIT
What about returning the config object?
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return {
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
}
};
The best idea would be to move Upload to the factory and return the promise.
factory.uploadDocument = function(id_location, name, description, file, locationUniqueId){
return Upload.upload({
method: 'POST',
url: $location.protocol() + '://' + $location.host() + '/rest/api/document/documents',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
id_location: id_location,
name: name,
description: description,
userFile: file,
locationUniqueId: locationUniqueId
}
});

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 JS contact form

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

Categories

Resources