Angular ajax submit form - php

I am having problem with ajax submit form with angular, when i click submit my entire page is reloaded?
Where can be the problem, here is my code
/*
Create the controller and inject Angular's $scope
*/
// resource2Controller
(function () {
'use strict';
angular.module("aluPlanetApp").controller('resource2Controller', resource2Controller);
resource2Controller.$inject = ['$scope'];
resource2Controller.$inject = ['$http'];
function resource2Controller($scope, $http) {
activate();
function activate() {
$scope.title = 'Contact';
$scope.id = '2';
$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 <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';
}
}
}
}
})();
And contact-form.php
<?php
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('something#test.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);
}
HTML
<div ng-controller="resource2Controller" 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" >
</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>

Mhh I belive that maybe your problem is in the HTML which I can't see right now so make sure that you are not using the submit button. I mean Instead of <input type="submit"... use <input type="button"...Here is a reference How do I make an HTML button not reload the page

On your HTML, you call your controller ContactController while at the Angular side you call it resource2Controller. Those two should match or Angular doesn't know what to do.

Related

PHP Contact form not working with bootstrap html

I'm fairly new to web development and PHP and i've been having trouble trying to get my contact form to work with the Bootstrap template
I am getting an error:
Error 405(Method Not Allowed):
send # jquery.min.js:2 ajax # jquery.min.js:2
(anonymous) # contact.js:18 dispatch # jquery.min.js:2
y.handle # jquery.min.js:2
contact.php
<?php
$from = "#example.com";
$sendTo = "#example.com";
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'subject' => 'Subject', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
index.html
<div class="main-form">
<div class="container">
<div class="row">
<!-- contact form -->
<div class="col-md-offset-2 col-md-8">
<form class="form" id="contact-form" method="POST" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="form_name" type="text" name="name" placeholder="Name *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_email" type="email" name="email" placeholder="Email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input id="form_subject" type="subject" name="subject" placeholder="Subject">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea id="form_message" name="message" placeholder="Message *" rows="4" required="required" data-error="Message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="col-sm-4">
<input type="submit" class="button" value="Send message">
</div>
</form>
</div>
</div>
</div>
</div>
Thank you for any help
javascript
$(window).on("load",function (){
$(".loading").fadeOut(500);
// contact form
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
});
});

Unable to implement reCaptcha in HTML Form

I am new to Web development and I am trying to implement reCaption in my HTML form.
I tried many online tutorials but I was unable to implement it propoerly in my code.
Head :
<script src="https://www.google.com/recaptcha/api.js?render=6LfRQZ4UAAAAAAuMMBQhrBVmyjkVsD"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfRQZ4UAAAAAAuMMBhzvMWVmyjkVsD', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>
Form :
<form id="ajax-contact" method="post" action="mailer.php">
<fieldset>
<div class="form-field">
<input type="text" id="name" name="name" placeholder="Full Name" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input type="email" id="email" name="email" placeholder="Email" value="" required="" aria-required="true" class="full-width"placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="telno" type="text" id="telno" placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="subj" type="text" id="subj" placeholder="Subject" value="" class="full-width">
</div>
<div class="form-field">
<textarea id="message" name="message" placeholder="Leave Message" value="" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
<div class="form-field">
<button id="submit" type="submit" name="submit" class="full-width btn--primary">SEND</button>
<div class="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
mailer.php :
<?php // Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6LfRQZ4UAAAAAJhdTvqgZyMJB-HO4XL_';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
// Verified - send email
} else {
// Not verified - show form error
}
} ?>
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$telno = trim($_POST["telno"]);
$subj = trim($_POST["subj"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "user#mail.com";
$subject = "New contact from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Telephone Number: $telno\n";
$email_content .= "Subject : $subj\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
app.js :
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-field');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #telno, #subj, #message').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
I want add reCatcha in this form to avoid spammers.
I tried official google docs also but I was unable to implement that properly in my code.
Thanks in advance for any solution.

Not Getting ajax success response using mamp

For some reason I am not getting a response back from AJAX call. I have used the console in Chrome and Firefox to monitor this but all I can see if what the form is sending. I am using MAMP and haven't tried this on a live server, but I need it to work in MAMP. I have tried lots of things people have suggested from similar issues I have found in stackoverflow but known have worked,please help!
<form id="signup_submit" method="post" action="AJAX/signup.php">
<div class="form-group show-progress">
</div>
<div class="form-group">
<input type="text" name="firstname" id="firstname" class="form-control" autocomplete="firstname" placeholder="Enter First Name...">
<span class="firstname-error error"></span>
</div><!-- form-group -->
<div class="form-group">
<input type="text" name="surname" autocomplete="surname" id="surname" class="form-control" placeholder="Enter Surname...">
<span class="surname-error error"></span>
</div><!-- form-group -->
<div class="form-group">
<input type="email" name="email" id="email" autocomplete="email" class="form-control" placeholder="Enter Email...">
<span class="email-error error"></span>
</div><!-- form-group -->
<div class="form-group">
<input type="password" name="password" autocomplete="password" id="password" class="form-control" placeholder="Choose Password...">
<span class="password-error error"></span>
</div><!-- form-group -->
<div class="form-group">
<input type="password" id="confirm" name="confirm" autocomplete="confirm" class="form-control" placeholder="Confirm Password...">
<span class="confirm-error error"></span>
</div><!-- form-group -->
<div class="form-group">
<button type="submit" id="submit" >Create Account</button>
</div><!-- form-group -->
<div class="form-group">
Already have an account?
</div>
</form><!-- form -->
signup.js
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
var data = $('#signup_submit').serialize();
console.log(data)
$.ajax({
type:'POST',
URL: 'AJAX/signup.php',
data: data,
dataType: 'json',
encode:true,
success: function(d){
d = JSON.parse(d);
console.log(d.testjson);
if(d.success){
$('#signup_submit').append('<div>'+d.message+'</div>');
}else{
if(d.errors.firstname){$('.firstname-error').show();$('.firstname-error').html(d.errors.firstname);}
if(d.errors.surname){$('.surname-error').show();$('.surname-error').html(d.errors.surname);}
if(d.errors.email){$('.email-error').show();$('.email-error').html(d.errors.emailname);}
if(d.errors.password){$('.password-error').show();$('.password-error').html(d.errors.password);}
if(d.errors.confirm){$('.confirm-error').show();$('.confirm-error').html(d.errors.confirm);}
}
}
})
})
})
signup.php
<?php
$errors = array();
$response = array();
if(empty($_POST['firstname'])){$errors['firstname'] = 'First Name Is Required!';}
if(empty($_POST['surname'])){$errors['surname'] = 'Surname Is Required!';}
if(empty($_POST['email'])){$errors['email'] = 'Email Address Is Required!';}
if(empty($_POST['password'])){$errors['password'] = 'Password Is Required!';}
if(empty($_POST['confirm'])){$errors['confirm'] = 'Please Confirm Your Password!';}
$response['errors'] = $errors;
if (!empty($errors)){
$response['success'] = false;
$response['message'] = 'FAIL!';
}else{
$response['success'] = true;
$response['message'] = 'SUCCESS!';
}
?>
You are never returning anything in the signup.php file. You need to json_encode and use echo or exit at the end of your script.
<?php
$errors = array();
$response = array();
if (empty($_POST['firstname'])) $errors['firstname'] = 'First Name Is Required!';
if (empty($_POST['surname'])) $errors['surname'] = 'Surname Is Required!';
if (empty($_POST['email'])) $errors['email'] = 'Email Address Is Required!';
if (empty($_POST['password'])) $errors['password'] = 'Password Is Required!';
if (empty($_POST['confirm'])) $errors['confirm'] = 'Please Confirm Your Password!';
$response['errors'] = $errors;
if (!empty($errors)) {
$response['success'] = false;
$response['message'] = 'FAIL!';
} else {
$response['success'] = true;
$response['message'] = 'SUCCESS!';
}
// Return data here
exit(json_encode($response));
?>
Edit: Keep the PHP exit from above, but instead use jQuery.post() rather than jQuery.ajax() as it is shorter, cleaner and simpler than messing with content types. It should also fix your issue:
$(document).ready(function(){
$('form').submit(function(e) {
e.preventDefault();
var data = $('#signup_submit').serialize();
console.log("data:");
console.log(data);
$.post("AJAX/signup.php", data, result => {
console.log("result:");
console.log(result);
result = JSON.parse(result);
if (result.success) {
$('#signup_submit').append('<div>'+result.message+'</div>');
} else {
if (result.errors.firstname) $('.firstname-error').html(result.errors.firstname).show();
if (result.errors.surname) $('.surname-error').html(result.errors.surname).show();
if (result.errors.email) $('.email-error').html(result.errors.email).show();
if (result.errors.password) $('.password-error').html(result.errors.password).show();
if (result.errors.confirm) $('.confirm-error').html(result.errors.confirm).show();
}
});
});
});
Remove dataType: 'json' and try. Also set the header before echoing back the result like below:
header('Content-type:application/json');
echo json_encode($response);

PHPMAILER not sending select input

Hi my question is about the following i'm using the select tag in my form, but the value does not get passed on to the email that gets send out.
I've created an app using PHPMAILER and have added the select tag with options included. whenever I hit send I get the following error:
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"contact-form.php","data":"inputPrice=1%20%2F%202%20hour%20%3D%2020%2C-&inputGuests=1&inputDate=Mon%20Feb%2003%201992%2010%3A10%3A00%20GMT%2B0100%20(Central%20European%20Standard%20Time)&inputMessage=Mon%20Feb%2003%201992%2010%3A10%3A00%20GMT%2B0100%20(Central%20European%20Standard%20Time)&inputName=Salman%20Mohamed&inputEmail=salmannova%40gmail.com&inputNumber=620438661","headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"abort"}
The email does get send with all the value's added except the value from the select tag. In the error you can read that the value does get passed on, but for some reason doesn't get passed onto the email.
Does anyone know what's wrong with my code?
Select module
<select ng-model="formData.inputPrice" type="number" class="form-control inputForm fa fa-input" id="inputPrice" name="inputPrice" placeholder="How many scooters?" required>
<option value="" disabled="disabled" selected="selected">Prices</option>
<option value="1 / 2 hour = 20,-">1 / 2 hour = 20,-</option>
<option value="1 day = 30,-">1 day = 30,-</option>
<option value="2 days = 55,-">2 days = 55,</option>
<option value="3+ dagen = +20,-">3+ dagen = +20</option>
</select>
mail.html
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
</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="steps stepOneWhite" id="stepOne">
<div class="form-group" ng-class="{ 'has-error': contactform.inputPrice.$invalid && submitted }">
<div class="col-lg-10">
<select ng-model="formData.inputPrice" type="number" class="form-control inputForm fa fa-input" id="inputPrice" name="inputPrice" placeholder="How many scooters?" required>
<option value="" disabled="disabled" selected="selected">Prices</option>
<option value="1 / 2 hour = 20,-">1 / 2 hour = 20,-</option>
<option value="1 day = 30,-">1 day = 30,-</option>
<option value="2 days = 55,-">2 days = 55,</option>
<option value="3+ dagen = +20,-">3+ dagen = +20</option>
</select>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputGuests.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputGuests" type="number" class="form-control inputForm fa fa-input" id="inputGuests" name="inputGuests" placeholder="How many scooters?" required>
</div>
</div>
<h2>Pick up</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputDate.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputDate" type="datetime-local" class="form-control inputForm fa fa-input" id="inputDate" name="inputDate" placeholder="Your Date" required>
</div>
</div>
<h2>Return</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputMessage" type="datetime-local" class="form-control inputForm fa fa-input" rows="4" id="inputMessage" name="inputMessage" placeholder="&#xf075" required></input>
</div>
</div>
</div>
<div class="steps stepTwoWhite" id="stepTwo">
<h2>Your Information</h2>
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control inputForm fa fa-input" id="inputName" name="inputName" placeholder="&#xf007" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control inputForm fa fa-input" id="inputEmail" name="inputEmail" placeholder="&#xf0e0" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputNumber.$invalid && submitted }">
<div class="col-lg-10">
<input ng-model="formData.inputNumber" type="number" class="form-control inputForm fa fa-input" id="inputNumber" name="inputNumber" placeholder="&#xf095" required>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary btn-lg btn-block submitInputWhite" id="submitInput" ng-disabled="submitButtonDisabled">
Send Message
</button>
<span id="rentButton" class="btn btn-primary btn-lg btn-block rentButtonWhite" onclick="rentNowWhite()">Rent!</span>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
</div>
</div>
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['inputNumber']) && isset($_POST['inputGuests']) && isset($_POST['inputDate']) && isset($_POST['inputMessage']) && isset($_POST['inputPrice'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputNumber']) || empty($_POST['inputGuests']) || empty($_POST['inputDate']) || empty($_POST['inputMessage']) || empty($_POST['inputPrice']) ) {
$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('salman-1992#hotmail.com'); //recipient
$mail->Subject = "Nieuwe reservering is binnengekomen";
$mail->Body = "Nieuwe reservering:". "\r\n\r\nNaam: " . $_POST['inputName'] . "\r\n\r\nTelefoonnummer: " . $_POST['inputNumber'] ."\r\n\r\nAantal Gasten: " . $_POST['inputGuests'] ."\r\n\r\nDatum: " . $_POST['inputDate'] . $_POST['inputMessage'] . $_POST['inputPrice']);
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);
}
controller.js
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; //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';
}
}
});

unable to post json data , response message is SyntaxError: unexpected token <

also i did not get any console error and i check network tab i get 200 ok message that means data is posted.. please help
Here is jquery code
$(document).ready(function() {
$('#mc_subscribe').submit(function() {
$('#response').html('form submitting....');
var form = $(this);
$.ajax({
url: $(this).prop('action'),
type: 'POST',
dataType: 'json',
data: form.serialize()
}).done(function(data){
if (data.success == true){
$('#mc_subscribe')[0].reset();
$('#response').addClass('alert-success').removeClass('alert-danger').html(data.message);
window.setTimeout(function() {
window.location.href = data.redirectURL;
}, 2000);
} else{
$('#response').addClass('alert-danger').removeClass('alert-success').html(data);
}
}).fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + data );
});;
return false;
});
});
Here is my codignitor controller code
class Subscribe extends CI_Controller {
private $data;
public function index() {
if ($this->input->is_ajax_request()){
$result = $this->_subscribe();
echo json_encode($result);
exit;
}
$this->load->view('header');
$this->load->view('pages/subscribe', $this->data);
$this->load->view('footer');
}
private function _subscribe(){
$success = true;
$redirectURL = base_url() + '/pricing';
if(!$this->input->post('FNAME')){
$message = "No Full Name provided";
$success = false;
}
if( empty($this->input->post('EMAIL')) || !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['EMAIL']) ){
$message = "No Email address provided";
$success = false;
}
if($success && !$this->input->post('MOBILE')){
$message = "No Phone Number provided";
$success = false;
}
if($success && !$this->input->post('DAYTIME')){
$message = "No Day & Time provided";
$success = false;
}
if ($success){
$this->load->library('Mcapi', array(
'apikey' => $this->config->item('mailchimp_key')
));
$api = new Mcapi($this->config->item('mailchimp_key'));
$list_id = $this->config->item('mailchimp_list_id');
$merge_vars = Array(
'FNAME' => $this->input->post('FNAME'),
'MOBILE' => $this->input->post('MOBILE'),
'DAYTIME' => $this->input->post('DAYTIME')
);
if($api->listSubscribe($list_id, $_POST['EMAIL'], $merge_vars, '') === true) {
// It worked!
$message = 'Success!';
} else {
$success = false;
// An error ocurred, return error message
$message = 'Error: ' . $api->errorMessage;
}
}
return array('message' => $message, 'success' => $success, 'redirectURL' => $redirectURL);
}
}
and here is HTML form
<div class="container">
<div class="col-md-12">
<form id="mc_subscribe" class="form-horizontal" action="http://localhost/CI-2/Subscribe/" method="post">
<fieldset>
<!-- Form Name -->
<legend>SUBSCRIBE</legend>
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-4">
<input id="" name="FNAME" type="text" placeholder="Full Name" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-4">
<input id="" name="EMAIL" type="email" placeholder="Email" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-4">
<input id="" name="MOBILE" type="text" placeholder="Phone Number" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-4">
<input id="" name="DAYTIME" type="text" placeholder="Day & Time" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for=""></label>
<div class="col-md-8">
<input type="submit" name="submit" class="btn btn-success" value="SUBSCRIBE">
</div>
</div>
</fieldset>
</form>
<p id="response" class="alert text-center" align="center"></p>
</div>
</div>
change this below line
return array('message' => $message, 'success' => $success, 'redirectURL' => $redirectURL);
TO
$data = array();
$data['message'] = $message ;
$data['success'] = $succcess;
$data['redirectURL'] = $redirectURL;
return json_encode($data);
in your controller.
it seems you are not returning the data in the json format,

Categories