I have an AngularJS app which has a mailer script written in PHP. I'm trying to refer to the PHP file via the angular $http service but I keep getting a 404 error when I try to use it via my contact form, in the corresponding controller, like so:
angular.module('myModule')
.controller('contactUsController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.submitted = false;
$scope.submit = function(contactform) {
console.log('Form data', $scope.formData);
$scope.submitted = false;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : "app/process.php",
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data){
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = "Sorry. Error sending message. Please try again.";
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.formData = {}; // form fields are emptied with this line
$scope.submissionMessage = "Thank you! Your message has been sent successfully.";
$scope.submitted = true; //shows the success message
}
});
} else {
}
}
}]);
So each time I invoke the submit() function by pressing the send button, the browser complains like so:
I've been searching around for an answer, but I haven't found one that could help me out.
I am using npm start to run my app. My project structure is as shown in the image below:
Any idea what could be going wrong? Any help is appreciated.
Related
I'm sorry if this is repeating previous questions, but i haven't been able to find a solution which seems to work with my problem & im new to Angular.
I have an Angular form, which communicates data with PHP to send an email, and my problem is with handling the JSON response from the PHP (as the PHP communicates back whether it succeeded within the JSON itself, along with a message).
I can't seem to get the code to respond based on the "success" value contained within the JSON, nor actually display the "message.
The JSON response data looks like this (when it fails due to an email issue):
So my angular code needs to respond based on "success" being true or false, while also displaying the "message" which is passed by AJAX in JSON.
My Angular Controller code:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false;
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
var request = $http({
method : 'POST',
url : 'php/contact.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
if (request.success) {
console.log(request);
$scope.submitButtonDisabled = false;
$scope.result='bg-success';
$scope.resultMessage = request.message;
} else {
$scope.submitButtonDisabled = true;
$scope.resultMessage = request.message;
//$scope.resultMessage = "Opps!... something went wrong. Please Contact OpenHouse directly to let them know of this error.";
$scope.result='bg-danger';
};
//};
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
My PHP Code:
<?php
require_once ("class.phpmailer.php"); // Include phpmailer class
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
if (isset($_POST['inputFirstName']) && isset($_POST['inputLastName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputFirstName']) || empty($_POST['inputLastName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
$message=
'First Name: '.$_POST['inputFirstName'].'<br />
Last Name: '.$_POST['inputLastName'].'<br />
Phone: '.$_POST['inputPhone'].'<br />
Email: '.$_POST['inputEmail'].'<br />
Comments: '.$_POST['inputMessage'].'
';
$mail = new PHPMailer(); // Instantiate the PHPMailer Class
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // SMTP authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled + REQUIRED for Gmail (either SSL or TLS)
$mail->Host = "smtp.gmail.com"; //Gmail SMTP Server to relay thru
$mail->Port = 465; // Port 465 as we're using SSL... or use Port 587 for TLS
$mail->IsHTML(true); // We're sending a HTML formatted message
$mail->Username = "....#gmail.com"; // Gmail account for authentication
$mail->Password = "*********"; // Gmail password for authentication
$mail->SetFrom("....#gmail.com"); // The email is being sent from this address
$mail->Subject = "Website Contact Form Enquiry"; // The subject line of the email
$mail->Body = ($message); // The actual email message to be sent
$mail->AddAddress("....#gmail.com"); // The email is being sent to this address
if(!$mail->send()) {
echo json_encode(['success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo]);
exit;
}
error_log("Data: ".$data['success']." Message: ".$data['message']);
echo json_encode(['success' => true, 'message' => 'Thanks! We have received your message.']);
} else {
echo json_encode(['success' => false, 'message' => 'Please fill out the form completely.']);
}
?>
To start, the $http does not return a request object, it returns a promise that resolves with a response object:
//var request = $http({
//It returns a promise
var promise = $http({
method : 'POST',
url : 'php/contact.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//Use .then method to receive response
promise.then(function (response) {
var request = response.data;
if (request.success) {
console.log(request);
$scope.submitButtonDisabled = false;
$scope.result='bg-success';
$scope.resultMessage = request.message;
}
});
It is important to realize that the $http service immediately returns a pending promise. The promise is later resolved (either fulfilled or rejected) when the response comes back from the server.
Use the .then method of the promise to provide success and rejection handlers that resolve with either the fulfilled or rejected response.
For more information, see: AngularJS $http Service API Reference - General Usage
UPDATE
The AngularJS framework by default encodes and posts using Content-Type: 'application/json'.
To receive JSON data in a PHP backend, do something like:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Then the POST with AngularJS can be simplified:
var promise = $http({
method : 'POST',
url : 'php/contact.php',
//data : $.param($scope.formData), //param method from jQuery
data: $scope.data;
//headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
//Defaults to:
//headers: {'Content-Type': 'application/json'}
});
//Use .then method to receive response
promise.then(function (response) {
var request = response.data;
if (request.success) {
console.log(request);
$scope.submitButtonDisabled = false;
$scope.result='bg-success';
$scope.resultMessage = request.message;
}
});
Thanks everyone for the help;
I was able to return a response after the asyn http call & display it on the screen...
But no matter what i tried, it always packages the HTTP headers with the data, within the data response.
If the PHP didn't send an email (I removed all commands for sending email), then the data response would be just data.
If the PHP did send an email, then the response would be HTTP headers + data within the data response.
So in the end on the Angular side, i converted the data response to a string, split that string based up { which would give me a new string with just the data (and no headers), some extra \separating the values in the string, and obviously and ending }
So thus, by string manipulation, i was able to get the response i wanted.
Here's the working Angular Controller:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false;
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
var promise = $http({
method : 'POST',
url : 'php/contact.php',
data : {
firstname: $scope.formData.inputFirstName,
lastname: $scope.formData.inputLastName,
emailid: $scope.formData.inputEmail,
phoneno: $scope.formData.inputPhone,
message: $scope.formData.inputMessage
},
headers : {'Content-Type': 'application/json'}
})
promise.then(function (response) {
var request = JSON.stringify(response.data); //convert JSON data to string for manipulation
var startpos = request.indexOf("{"); //locate '{' as its the start of the data we want
var endpos = request.lastIndexOf("}"); //locate '}' as its the end of the data we want
var res = request.slice(startpos, endpos); //Extract the actual data now we know where it is.
var newresponse = res.split("\\"); //Split the data into new array
var answer = request.search("true"); //search the string to see if it contains the word "true" meaning an email was sent.
if (answer >= 0) {
$scope.submitButtonDisabled = false;
$scope.result='bg-success';
$scope.resultMessage = newresponse[5].replace('"', " ");
} else {
$scope.submitButtonDisabled = true;
$scope.resultMessage = newresponse[5].replace('"', " ");
$scope.result='bg-danger';
}
});
}
});
I am a new Angularjs user.I am facing a problem,when i submit a signup form,I have applied validation using AngularJs. At the same time if all the input fields are valid then i have send an $http Ajax call to check the email address,already exist or not.The issue is my php file did not receive email data.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data: { email: $scope.user.email }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
My Php file code:
$email = $_POST['email'];
$sql = "SELECT * FROM user where username = '".$email."'";
$result = mysql_query($sql);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
....
....
....
....
....
}
I have checked and found that php file did not receive email value at all.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data : $.param($scope.user), // this will definitely wor
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
Try removing http://localhost from url and then see it may be CORS.
Just a guess: your url is pointing to localhost but has no port number, this is unusual, maybe you forgot it?
data: $.param({
email:$scope.user.email
})
Or this way: (modify the php)
Angular HTTP post to PHP and undefined
I have just found that in php file,
$_POST or $_GET will not work, to receive data.
Use the following:
$data = file_get_contents("php://input");
$objData = json_decode($data);
$email = $objData->email;
In my case it works.
I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));
here's my issue:
I did a very basic angularJS app which is supposed to get data from a php file and bind them into the scope. So the php file (linked to MySQL DB) output is:
[{"hum":"55.36","temp":"20.86","unixtime":"2015-10-29 17:39:42","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"},
{"hum":"55.33","temp":"20.84","unixtime":"2015-10-29 17:39:50","coreid":"xxxxxx","moist":"0.00","volt":"4.30","soc":"114"},
{"hum":"55.42","temp":"20.84","unixtime":"2015-10-29 17:39:58","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"}]
The app's code is:
var dashb = angular.module('dashboard', []);
//avoid cross domain issue
dashb.config(['$httpProvider', function($httpProvider) {
$http.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
dashb.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get("http://www.domain.com/php_file_url.php")
.success(function(data) {
$scope.data = data;
$scope.hum = data.hum;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
But when I run it it doesn't work. I get no data. What do I do wrong? Thank you
If you're sure you're getting data from your query, you just need to send it as JSON. Add this before the echo $res; line:
header('Content-Type: application/json');
Also, in your code, change the following
$http.defaults.useXDomain = true;
to
$httpProvider.defaults.useXDomain = true;
I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");