I've been stuck on this for days.
Basically I have a $http.post with Angular, posting an e-mail address and message to be emailed from post.php. Post.php is then echoing text depending on the result of the mail(), but when I return
Success
for example, it will actually show the HTML on the DOM instead of process it.Appreciate any help.
app.controller('contactsController', function($scope, $rootScope, $http) {
$rootScope.currentPage = "contact";
$scope.postData = {};
$scope.data = "Send";
$scope.runScript = function() {
$http({
url: "post.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({"postData":$scope.postData})
}).success(function(data) {
$scope.data = data;
console.log(data);
$scope.contactForm.$valid = false;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
<?php
// get the raw POST data
$inputData = $_POST['postData'];
if(isset($inputData["email"])&&isset($inputData["message"])) {
$email = $inputData["email"];
$message = $inputData["message"];
$to = "XXXXXXXXXXXXX@XXXXXXXXXX.COM"; // required
$from = $email; // required
$body = $message;
$subject = "Online Query Submission";
// create email headers
if(mail($to,$subject,$body,"From:$from/r/nReply-to:$from"))
echo "<p>Success - Thanks!</p>";
else
echo "<p>Error - Sorry!</p>";
}
?>
I believe you should use ng-bind-html
in your view, like so:
<div ng-bind-html="data"></div>
as you attribute the message returned from the server to a controller $scope variable, like so:
$http(url).success(function(data){
$scope.data=data;
});
From angularjs doc about ngBindHtml,
ng-bind-html
evaluates the expression and inserts the resulting HTML into the element in a secure way
You can possibly find what you want here AngularJS : Insert HTML into view
However, I think it will be a good practice to make PHP return just a confirmation text and formate it on the front end using Angular.
Although everybody has helped fantastically, ng-bind-html="data"
was part of the problem.
The remaining problem was that I didn't realise ngSanitize
was a requirement, get it in as a dependency and it works perfect :)
I believe there is a quicker way to bypass ngSanitize, something like $sce.trustAsHtml
, but not considered a good practice I believe.