Getting null response to Recaptcha V3 with ajax - php

I'm having a problem with getting a problem when submitting captcha v3 to ajax. I get a null response to Google. I have tried multiple tutorials but I think it does not fix to ajax request.
I think the problem is with google or my php, or ajax request. I understand my codes but I am not familiar with using google's code like this captcha v3. I have use captcha v2 before. And now I am trying v3 I can't run it with my code.
Here is my Ajax and HTML code :
// when form is submit
$('.contact-form').submit(function (event) {
// we stoped it
event.preventDefault();
var url = $(this).prop('action');
var contact_data = $(this).serialize();
$('.btn-contact').html('<em class="fas fa-spinner fa-pulse"></em> Sending...');
$('.alert').fadeOut('slow');
// needs for recaptacha ready
grecaptcha.ready(function () {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Ldjp6Q[--my site key---]8H5bxI1', { action: 'create_contact' }).then(function (token) {
// add token to form
$('.contact-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
var contact = function () {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: contact_data, token: token ,
success: function (response) {
$('.message').html(response.message);
$('.btn-contact').html('<em class="fas fa-paper-plane"></em> Send');
if (response.error) {
$('.status').removeClass('alert-success').addClass('alert-danger').show();
}
else {
$('.status').removeClass('alert-danger').addClass('alert-success').show();
$('.contact-form')[0].reset();
}
}
});
};
setTimeout(contact, 3000);
});;
});
});
<?=form_open('Contact/Send_Contact', array('class' => 'contact-form'))?>
<div class="row top-2">
<div class="col-md-12">
<div class="status alert text-center" style="display:none;">
<button type="button" class="close clearMsg"><span aria-hidden="true">×</span></button>
<span class="message"></span>
</div>
</div>
<div class="form-group col-md-6">
<input type="text" placeholder="Your Name" name="name" class="form-control name">
<div class="invalid-feedback invalid-name"></div>
</div>
<div class="form-group col-md-6">
<input type="email" placeholder="Your Email" name="email" class="form-control email">
<div class="invalid-feedback invalid-email"></div>
</div>
<div class="form-group col-md-12">
<input type="text" placeholder="Subject" name="subject" class="form-control subject">
<div class="invalid-feedback invalid-subject"></div>
</div>
<div class="form-group col-md-12">
<textarea placeholder="Message" class="form-control message_text" name="message" rows="4"></textarea>
<div class="invalid-feedback invalid-message"></div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-info btn-contact float-right"><em class="fas fa-paper-plane"></em> Send</button>
</div>
</div>
</from>
<script src="https://www.google.com/recaptcha/api.js?render=6Ldj[--My site key--]5bxI1"></script>
And I also copied some PHP code and I don't know where is the problem here because this is my first time using CodeIgniter and I also haven't used captcha v3 too.
Please review my PHP code here :
public function Send_Contact() {
$output['error'] = true;
$output['message'] = 'Please fill up the error field(s).';
$name = $this->input->post('name');
$email = $this->input->post('email');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
$captcha = $this->input->post('token');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if($this->form_validation->run() === false) {
//some codes here I remove because it has nothing to do with the question.
die(json_encode($output));
}
if(!$captcha){
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
$secretKey = "6Ldjp[--My secret key--]YQL_";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $captcha);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
if($this->contact_model->create_contact()) {
$output['error'] = false;
$output['message'] = 'Thank you for sending message! <em class="far fa-check-circle"></em>';
echo json_encode($output);
} else {
$output['error'] = true;
$output['message'] = 'Error in database model.';
echo json_encode($output);
}
} else {
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
}
I'm using codeigniter 3. and this public function is in the contact controller.

Related

PHP validation always returns error/false in ajax even the conditions are true

I have only two conditions.
If the yourname is empty return error
If the email is empty returns error
but I get error even if both are not empty.
I could not figure out why.
My Form
<form action="" method="post" name="contact-me" id="profile-update" class="requires-validation">
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-key fa-lg me-3 fa-fw"></i>
<div class="d-flex form-floating mb-0 flex-fill">
<input name="yourname" type="text" class="form-control name" placeholder="Type your name" >
<label for="yourname" class="form-label">Your Name</label>
<div class="yournameerror">Name field is valid!</div>
</div>
</div>
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-key fa-lg me-3 fa-fw"></i>
<div class="d-flex form-floating mb-0 flex-fill">
<input name="email" type="email" class="form-control" placeholder="Type a valid email" >
<label for="email" class="form-label">Your Email</label>
<div class="emailerror">Name field is valid!</div>
</div>
</div>
<div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
<button type="submit" class="btn btn-primary btn-lg" id="submit">Send message!</button>
</div>
<div id="nds_form_feedback"></div>
</form>
Validation function
<?php
function stack_update_validation_func(){
$errors = array();
$response = array();
$yourname=$_POST['yourname'];
$email=$_POST['email'];
if ($_POST['yourname'] == '') {
$errors['yourname'] = "Please enter your name";
}
if ((empty($_POST['email'])) ) {
$errors['email'] = "Please enter your email";
}
$response['errors'] = $errors;
if($errors !== '') {
$response['success'] = false;
$response['message'] = "Fail";
} else {
$reponse['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
header("Content-Type: application/json", true);
echo json_encode($response);
wp_die();
}
Getting that JSON response in this Ajax:
Please read the comments as well
<script type="text/javascript">
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var data = new FormData();
data.append('action', 'stack_update_validation_func');
jQuery.ajax({
type: 'POST',
url: ajax_url,
data: data,
contentType: false, //because I have a file upload feild as well
processData: false, //because I have a file upload feild as well
headers: {Accept : "application/json;charset=utf-8"},
dataType: 'json',
debug:true,
success: function(response) {
if(response.success) {
jQuery("#nds_form_feedback").html('Sucessfully Sent'); // if the form passes the validation this works fine
}
else {
alert("Not Uploaded"); // shows the popup if there is a validation error
jQuery.each(response.errors, function(key, val) {
console.log(key); // returns the key like this https://prnt.sc/I4R0rNdRIF0o
});
console.log(response); // returns the json response in console
jQuery.each(response.errors, function(key, val) {
jQuery('#profile-update [name="'+key+'"]').parent().find('.'+key+'error').html(val);
});
}
}
});
});
</script>
console.log(response); shows this
but the issue is even yourname and email are filled correctly the error message is shown.
not sure what is wrong. please help.
In your method stack_update_validation_func there is a condition if($errors !== '') {. This condition will always be true because $errors will never be an empty string. It is initialized as empty array. So you should update the condition and your method could look like this:
function stack_update_validation_func()
{
$errors = array();
$response = array();
$yourname = $_POST['yourname'];
$email = $_POST['email'];
if ($_POST['yourname'] == '') {
$errors['yourname'] = "Please enter your name";
}
if (empty($_POST['email'])) {
$errors['email'] = "Please enter your email";
}
$response['errors'] = $errors;
if(!empty($errors)) {
$response['success'] = false;
$response['message'] = "Fail";
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Article added</div>";
}
header("Content-Type: application/json", true);
echo json_encode($response);
wp_die();
}
Update: Here is also the part of the JavaScript, that had to be updated:
// instead of `var data = new FormData();`
var data = new FormData(document.getElementById('profile-update'));

AJAX Contact form unable to find API Route, throwing 404 Error in console in Codeigniter 4

i have a user profile page (index.php | View) where any user can fill the contact form and send a message to particular user(whose profile is open). when i am trying to submit from it give me 404 Error and unable to find the route for contact_user Controller function.
here is my code for the same
here is the contact form code from profile view
<!-- Contact -->
<section class="resume-section" id="contact">
<div class="resume-section-content">
<h2 class="mb-5">Contact</h2>
<form method="POST" name="contact_us_form" id="contact_us_form">
<?php
foreach ($user_data as $key) {
?>
<input type="hidden" id="user_id" name="id" value="<?= $key->user_id ?>">
<?php
}
?>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_name" name="contact_form_name"
placeholder="Your Name">
<span class="text-danger" id="error_name"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_mobile" name="contact_form_mobile"
placeholder="Your Mobile" pattern="[1-9]{1}[0-9]{9}">
<span class="text-danger" id="error_mobile"></span>
</div>
<br>
<div class="form-group">
<input type="email" class="form-control" id="contact_form_email" name="contact_form_email"
placeholder="Your Email">
<span class="text-danger" id="error_email"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_subject" name="contact_form_subject"
placeholder="Message Subject">
<span class="text-danger" id="error_subject"></span>
</div>
<br>
<div class="form-group">
<textarea class="form-control" id="contact_form_message" name="contact_form_message"
placeholder="Message" rows="3"></textarea>
<span class="text-danger" id="error_message"></span>
</div>
<br>
<div class="form-group">
<div class="thankyou-message" id="thankyou-message" style="color:green"></div>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" id="contact_us" name="contact_us" value="SUBMIT">
</form>
</div>
</section>
here is my javascript Ajax code
jQuery('#contact_us_form').on('submit', function(e){
// alert('hello');
e.preventDefault();
// Name Validation
if ($.trim($('#contact_form_name').val()).length == 0) {
error_name = 'Please enter your name';
$('#error_name').text(error_name);
} else {
error_name = '';
$('#error_name').text(error_name);
}
// Mobile Validation
if ($.trim($('#contact_form_mobile').val()).length == 0) {
error_mobile = 'Please enter your Mobile';
$('#error_mobile').text(error_mobile);
} else {
error_mobile = '';
$('#error_mobile').text(error_mobile);
}
// Email Validation
if ($.trim($('#contact_form_email').val()).length == 0) {
error_email = 'Please enter your Email';
$('#error_email').text(error_email);
} else {
error_email = '';
$('#error_email').text(error_email);
}
// Subject Validation
if ($.trim($('#contact_form_subject').val()).length == 0) {
error_subject = 'Please enter Message Subject';
$('#error_subject').text(error_subject);
} else {
error_subject = '';
$('#error_subject').text(error_subject);
}
// Message Validation
if ($.trim($('#contact_form_message').val()).length == 0) {
error_message = 'Please enter Your Message';
$('#error_message').text(error_message);
} else {
error_message = '';
$('#error_message').text(error_message);
}
if (error_name != '' || error_mobile != '' || error_email != '' || error_subject != '' ||
error_message != '') {
return false;
}else{
var data = {
'user_id': $('#user_id').val(),
'contact_name': $('#contact_form_name').val(),
'contact_mobile': $('#contact_form_mobile').val(),
'contact_email': $('#contact_form_email').val(),
'contact_subject': $('#contact_form_subject').val(),
'contact_message': $('#contact_form_message').val(),
};
$.ajax({
method: "post",
url: "/Home/contact_user",
// headers: {'X-Requested-With': 'XMLHttpRequest'}
data: data,
success: function(response){
jQuery('#contact_us_form')['0'].reset();
jQuery('#contact_us').val('SUBMIT');
jQuery('#contact_us').attr('disabled', false);
alertify.set('notifier','position', 'top-right');
alertify.success("Done");
// response.preventDefault();
}
});
}
});
here are my Routes
$routes->get('/', 'Home::index'); // Default route, if no username redirect to welcome view
$routes->post('/Home/contact_user', 'Home::contact_user'); //contact form API Route, submit form data to this route
$routes->get('/(:any)', 'Home::user/$1'); // User Profile, if username found, show user profile
and here is my contact_user function from Home Controller
public function contact_user(){
$Home_Model = new \App\Models\Home_model();
$data = [
'user_id' => $this->request->getPost('user_id'),
'contact_name' => $this->request->getPost('contact_name'),
'contact_mobile' => $this->request->getPost('contact_mobile'),
'contact_email' => $this->request->getPost('contact_email'),
'contact_subject' => $this->request->getPost('contact_subject'),
'contact_message' => $this->request->getPost('contact_message')
];
$Home_Model->save($data);
$data = ['status' => 'successful'];
return $this->response->setJSON($data);
}

How to send information to database without reloading the page

I've been trying to send information to the database using AJAX but nothing is working, each time i click the submit button, nothing works, the pages stays static somewhat. All JS files are referenced properly so i'm not sure what i'm doing wrong.
Here's what i've done so far;
Controller:
public function contact_us_ajax() {
//form validation rules and file upload config
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
$this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
$this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
array(
'required' => 'Captcha is required. Reload the page if you cannot see any code.',
'matches' => 'Invalid captcha code'
)
);
if ($this->form_validation->run()) {
$this->message_model->contact_us(); //insert the data into database
$res = ['status' => true, 'msg' => 'Message sent successfully!'];
echo json_encode($res);
} else {
$res = ['status' => false, 'msg' => validation_errors()];
echo json_encode($res);
}
}
Model:
public function contact_us() {
$name = ucwords($this->input->post('name', TRUE));
$email = $this->input->post('email', TRUE);
$subject = ucwords($this->input->post('subject', TRUE));
$message = ucfirst($this->input->post('message', TRUE));
$message = nl2br($message);
$data = array (
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message,
);
$this->db->insert('contact_messages', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
View:
<?php
$form_attributes = array("id" => "contact_us_form");
echo form_open('home/contact_us_ajax', $form_attributes); ?>
<!-- Contact Form -->
<div class="col-md-5">
<h4>Send Us a Message</h4>
<div class="form-group">
<label>Name:</label><input type="text" name="name" class="form-control input-field" required>
<label>Email:</label><input type="email" name="email" class="form-control input-field" required>
<label>Subject:</label><input type="text" name="subject" class="form-control input-field" required>
</div>
<label>Message:</label>
<textarea name="message" class="textarea-field form-control" rows="4" required></textarea>
<div class="col-md-6">
<input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />
</div>
<div class="col-md-6">
<input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />
</div>
<div id="status_msg"></div>
<?php echo flash_message_success('status_msg'); ?>
<?php echo flash_message_danger('status_msg_error'); ?>
<button class="btn center-block">Send message</button>
</div>
<?php echo form_close(); ?>
AJAX:
//Contact Us
$('#contact_us_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'home/contact_us_ajax',
type: 'POST',
data: form_data,
dataType: 'json',
success: function(res) {
if (res.status) {
$( '#status_msg' ).html('<div class="alert alert-success text-center" style="color: #000">'+res.msg+'</div>').fadeIn('fast');
$('#contact_us_form')[0].reset(); //reset form fields
$('#captcha_code').val(''); //clear captcha field
setTimeout(function() {
location.reload();
}, 5000);
} else {
$( '#status_msg' ).html('<div class="alert alert-danger text-center" style="color: #000">' + res.msg + '</div>').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );
}
}
});
});
base_url is defined in codeigniter's config.php, for example like:
$config['base_url'] = 'http://or.org/';
BUT! This doesn't mean you can simply name a variable in javascript base_url and hope to get any value.
To use it in your ajax call, you need to echo the php constant out like:
url: '<?php echo base_url()?>' + 'home/contact_us_ajax'
I normally just use the relative path
url: '/home/contact_us_ajax'
which works fine as well, if you use a "regular" CI configuration

how to validate form input field if form value inserted through jquery?

view:
<script>
$(function(){
$( "#insert" ).click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text('Your Enquiry Has Been Sent. We Will Inform You Soon.');
$('#name,#email,#message,#phone').val('');
}
});
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Header</h4>
</div>
<div class="modal-body" id="bg-image">
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data">
<input type="text" class="form-control1" id="name" name="name" placeholder="Enter Your Name" required>
<input type="text" class="form-control1" id="email" name="email" placeholder="Enter Your Email Id" required>
<input type="text" class="form-control1" id="phone" name="phone" placeholder="Enter Your Phone" required>
<textarea class="form-control1" name="message" id="message" placeholder="Enter Your Message" required></textarea>
<input type="submit" name="insert" id="insert" value="Submit">
</form>
</div>
<div class="col-md-6">
<h4>Features</h4>
</div>
</div>
</div>
<div class="modal-footer">
<h4>Fotter</h4>
</div>
</div>
</div>
</div>
controller:
public function register()
{
$register = $this->Fetch_data->contact();
if(!empty($register_user))
{
return true;
}
else
{
return false;
}
}
models:
public function contact()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'message' => $this->input->post('message'),
's_date' => date('Y-m-d')
);
$this->db->insert('contact', $data);
}
In this code I have create a form inside the modal where I am inserting form value into database table name contact. Here, form value are inserting successfully but the validation are not working properly. If input field empty they show nothing like field is mandatory. So, How can we give validation to all field please help me ?
Thank You
Try This
Replace <script> To
<script>
$(function(){
$( "#insert").click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
dataType:'JSON',
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text(data.message);
}
});
});
});
</script>
Controller
public function register()
{
$this->load->library('form_validation');
$post = $this->input->post();
if (!empty($post)) {
//validate form input
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'E-mail', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() == true) {
$register = $this->Fetch_data->contact($post);
if (!empty($register)) {
echo json_encode(array("status" => false, "message" => "Inserted Successfully"));
exit(0);
} else {
echo json_encode(array("status" => false, "message" => "Unable to insert Try later"));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => validation_errors()));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => "Invalid Request"));
exit(0);
}
}
Model
public function contact($post)
{
$data = array(
'name' => $post['name'],
'email' => $post['email'],
'phone' => $post['phone'],
'message' => $post['message'],
's_date' => date('Y-m-d', time())
);
$this->db->insert('contact', $data);
return $this->db->insert_id();
}
If You got any error then let me know
Note
Note : Enable Form_validation library

Simple AngularJs Contact Form with PHP getting: Unexpected request: POST contact-form.php

I have never created an AngularJs contact form, and have tried a couple different examples on the web. In none of the examples is the error: Unexpected request: POST contact-form.php (or whatever the php file is named) mentioned (although there are a couple posts regarding "unexpected request", but these seem to be about $httpBackend or other topics), or any additional dependencies that needs to be injected etc.
Note: I am using a regular, out-of-the-box web hosting service.
I would appreciate if you could give me some input as to why I am getting this error, and perhaps what I am doing wrong, and any other useful tips.
Here is my controller code:
(function () {
"use strict";
angular
.module("impi-app")
.controller("ContactController",
["$scope", "$filter", "$http", '$location',
ContactController]);
function ContactController($scope, $filter, $http, $location) {
$scope.title = "Contact";
$scope.formData = {};
$scope.submit = function (contactForm) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function (contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method: 'POST',
url: 'contact-form.php',
data: $.param($scope.formData), //param method from jQuery
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function (data) {
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}
}
}());
here is my contact view:
<div class="vertical-middle">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Contact Form</h2>
</div>
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
</div>
</div>
</div>
here is my contact-form.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('onmyway.whatever#outlook.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
Much appreciated.
Try to add slash before contact-form.php
$http({
method: 'POST',
url: '/contact-form.php',
data: $.param($scope.formData), //param method from jQuery
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
})

Categories