I am trying to get a contact form up and running for a portfolio website. I understand design, but have a very limited understanding of development/server side issues.
The form functions as expected, BUT when submitted the form returns "..sending" and things stop there. I do not receive an email, and the status does not progress.
My site is hosted on Hostinger, who does not utilize Apache (of which I have no understanding). However, from what I have read, I do need some type of php server like apache to make this form function. The host says that they do support Ajax and that the emails are not being blocked.
I am trying to use Ajax, with validate script, and php to allow form submission without leaving the current page as follows: (this is a MDB form). This is a link to the hosted site for reference: https://intakt-design.com
I am receiving this error in dev tools: Uncaught reference error: sendMessage() is not defined at validate form
I feel like this is the problem, but I don't know what goes here, and google is leading me in circles...
code snippet link: https://mdbootstrap.com/snippets/jquery/marcin-luczak/2705367
Please excuse my ignorance, I'm new to web design (graphic design student), in general, and backend development is way over my head.
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "story#intakt-design.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email Delivered! Thanks for contacting inTakt Design!', 'code' => 1));
exit();
?>
HTML:
<!-- Contact Form -->
<div class="contact-content py-5">
<section class="mb-4 col-11 col-sm-10 col-lg-8 mx-auto mt-0 mb-3 form">
<!--Section heading-->
<h2 class="h1-responsive font-weight-bold text-center p-3 my-4 form-text form-head">Just Fill in the Blanks!</h2>
<!--Section description-->
<p class="text-center w-responsive mx-auto mb-5 form-text form-subhead">Do you have any questions or inquiries? Please do not hesitate to contact me directly.<br />I will typically respond within 24 hours.</p>
<div class="row">
<!--Grid column-->
<div class="col-md-9 mb-md-0 mb-5">
<form id="contact-form" name="contact-form">
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-6 form-field-containers">
<div class="md-form mb-0 form-field-containter">
<input type="text" id="name" name="name" class="form-control">
<label for="name" class="form-text form-field mt-n1">Your name</label>
</div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-6 form-field-containers">
<div class="md-form mb-0 form-field-container">
<input type="text" id="email" name="email" class="form-control">
<label for="email" class="form-text form-field mt-n1">Your email</label>
</div>
</div>
<!--Grid column-->
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<div class="col-md-12 mt-3 form-field-containers">
<div class="md-form mb-0 form-field-container">
<input type="text" id="subject" name="subject" class="form-control">
<label for="subject" class="form-text form-field mt-n1">Subject</label>
</div>
</div>
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-12 mt-3">
<div class="md-form message-container">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea p-2 message waves-effect"></textarea>
<label for="message" class="form-text form-field mt-n1 message-label"><span class="message-canned-txt italic">Type Your Message Here</span></label>
</div>
</div>
</div>
<!--Grid row-->
</form>
<div class="text-center text-md-left">
<a class="btn btn-rounded waves-effect cta-btn-res col-12 col-lg-5 mt-3 mb-0" onclick="validateForm();">Submit</a>
</div>
<div class="status" id="status"></div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-3 text-center">
<ul class="list-unstyled mb-0">
<li><br />
Connect with Me!
</li>
<li><br />
+ 501 259 6907
</li>
<li><br />
story#intakt-design.com
</li>
</ul>
</div>
<!--Grid column-->
</div>
</section>
<!--/ Contact Form-->
JS:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="popper.js"></script>
<script type="text/javascript" src="js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="js/mdb.js"></script>
<script type="text/javascript" src="js/mdb.pro.js"></script>
<!--Custom scripts-->
<script>
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.querySelector('.status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.querySelector('.status').innerHTML = "Email cannot be empty";
return false;
}
else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!re.test(email)){
document.querySelector('.status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.querySelector('.status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.querySelector('.status').innerHTML = "Message cannot be empty";
return false;
}
document.querySelector('.status').innerHTML = "Sending...";
sendMessage();
}
function sendMessge() {
formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $('textarea[name=message]').val()
};
$.ajax({
url : "mail.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#status').text(jqXHR);
}
});
}
</script>
I don't know why, but for some unusual reasons the sendMessage is not working. Try to rename the function. messageSending() in your js file and call it in your validateForm() function.
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.querySelector('.status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.querySelector('.status').innerHTML = "Email cannot be empty";
return false;
}
else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!re.test(email)){
document.querySelector('.status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.querySelector('.status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.querySelector('.status').innerHTML = "Message cannot be empty";
return false;
}
document.querySelector('.status').innerHTML = "Sending...";
messageSending();
}
function messageSending() {
document.querySelector('.status').innerHTML = "123Sending...";
formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $('textarea[name=message]').val()
};
$.ajax({
url : "mail.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#status').text(jqXHR);
}
});
}
Related
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'));
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);
}
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.
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)
})
I just made a login system but I can only login with pressing the button on my screen, not using the enter button on my keyboard. How can I enable this? I read something about the AcceptButton, but how do I apply this?
my code:
login.php
<?php
require('inc/functions.php');
session_start();
if(checkLogedIn()){
header("location:index.php");
die();
}
include 'inc/header.php'
?>
<body>
<div id="wrap">
<div class="text-center">
<img src="img/logo.png" height="125" width="125">
</div>
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">Inloggen</div>
<div class="result"></div>
<div class="panel-body">
<form role="form" id="loginForm">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Gebruikersnaam" name="username" type="text" autofocus="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Wachtwoord" name="password" type="password">
</div>
<div class="row">
<div class="col-xs-7">
Inloggen
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div><!-- /.col-->
</div><!-- /.row -->
</div>
<footer class="footer">
<div class="text-center">
<p class="text-muted">© <?php echo date("Y"); ?> company name</p>
</div>
</footer>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('.result').hide();
$(".post").on("click",function(){
// console.log('clicked!');
var formData = $('#loginForm').serialize();
$.ajax({
type: "POST",
url: "checkauth.php",
data: $("#loginForm").serialize(), // serializes the form's elements.
success: function(data){
//window.location.href = "/welcome";
// console.log(data);
if(data.status2 == 'success'){
//
$('.panel-body').fadeOut(1400);
$('.result').html(data.message);
$('.result').fadeIn(1200);
window.setTimeout(function() {
window.location.href = 'index.php';
}, 2000);
}else {
$('.result').html(data.message);
}
}
});
});
});
</script>
</body>
</html>
checkauth.php
<?php
session_start();
/* Check Login form submitted */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
/* Define username and associated password array */
$logins = array('admin' => 'admin2',
'username1' => 'password1',
'username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['username']) ? $_POST['username'] : '';
$Password = isset($_POST['password']) ? $_POST['password'] : '';
// print_r($_POST);
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
$_SESSION['UserData']['loggedin']=TRUE;
$return['message'] = '<br><div class="alert alert-success" role="alert">Login gegevens correct, welkom!</div><br>';
$return['status2'] = 'success';
} else {
/*Unsuccessful attempt: Set error message */
$return['message'] = '<div class="alert alert-danger" role="alert">Incorrecte login gegevens. Probeer het aub. opnieuw.</div>';
$return['status2'] = 'error';
}
echo json_encode($return);
}
else{
exit('No direct acces to this script!');
}
?>
Can anyone help ?
To make enter button to work you can use
<input type="submit">
Rather then
Inloggen
You can trigger the click on enter:
$(document).keydown(function(e){
var c = e.which;
e.stopPropagation();
if(c==13){
e.preventDefault();
$(".post").trigger("click");
}
});
You can modify your click as:
$('#loginForm').keypress(function (e) {
if(e.keyCode=='13') //Keycode for "Return"
$('#login').click();
}});