AngularJS PHP contact cannot read property name - php

Basically I have a contact form made with angularJS and PHP. and thats hosted on 000webhost. When I'm sending a mail the mail goes through but it also gives me an error. I think thats the reason it doesnt display MessageSuccess or MessageError messages.
TypeError: Cannot read property 'name' of undefined
at app.js:119
at angular.min.js:81
at angular.min.js:112
at m.$get.m.$eval (angular.min.js:126)
at m.$get.m.$digest (angular.min.js:123)
at m.$get.m.$apply (angular.min.js:127)
at l (angular.min.js:81)
at P (angular.min.js:85)
at XMLHttpRequest.H.onload (angular.min.js:86)
the HTML:
<div id="websiteApp" class="contactRow" style="display: none;">
<form ng-submit="submitForm()" ng-controller="FormController" novalidate class="contactForm" name="form" ng-hide="loaded">
<input class="input" type="text" name="name" placeholder="SINU NIMI" ng-model="formData.name" ng-class="{'error' : errorName}">
<input class="input2" type="email" name="email" placeholder="SINU E-MAIL" ng-model="formData.email" ng-class="{'error' : errorEmail}">
<textarea name="message" ng-class="{'error' : errorTextarea}" placeholder="KIRJUTA MEILE" ng-model="formData.message" rows="5"></textarea>
<input class="saada" type="submit" value="SAADA!" name="submit">
<div ng-class="{'submissionMessage' : submission}" ng-bind="submissionMessage"></div>
</form>
</div>
App.js
var app = angular.module('kaidoweb', ['ngRoute', 'ngAnimate']).
config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'pages/index.html',
activetab: 'index',
controller: HomeCtrl
}).
otherwise({ redirectTo: '/' });
}]).run(['$rootScope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.part = $route.current.activetab;
});
}]);
/*app.config(['$locationProvider', function($location) {
$location.hashPrefix('!');
}]);*/
//Contact form
app.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
};
});
and the PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
$data['messageError'] = 'Vaata üle punased alad!';
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['messageSuccess'] = 'Tänan, et kirjutasid. Võtan ühendust nii pea kui saan.';
// CHANGE THE TWO LINES BELOW
$email_to = "email.to#khk.ee";
$email_subject = "KaidoWeb kiri";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
Also another thing is I also host this site on GoDaddy when trying to send a mail there it says: POST http://www.kaidoweb.com/process.php 403 (Forbidden).
I would be immensely grateful if someone could give me some sort of solution here and if you need to see something more just ask.

This is how your PHP is setting the errors object it is returning to your Angular App:
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
As you can see, in each case it is setting a different key inside of the errors array. In your Angular code you don't account for this, you just assume that all of the keys will be set:
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
You can fix this either in your PHP or in your Angular App. In PHP, you could use an integer array rather than an associative array:
if (empty($_POST['name']))
$errors[] = 'Name is required.';
if (empty($_POST['email']))
$errors[] = 'Email is required.';
if (empty($_POST['message']))
$errors[] = 'Message is required.';
Then in Angular just set the scope variable and modify the view with how it's displayed:
$scope.errors = data.errors;
<ul><li data-ng-repeat="error in errors">{{ error }}</li></ul>
Alternatively, in Angular just check if the keys are set before attempting to access them:
if(data.errors.hasOwnProperty('name') {
$scope.errorName = data.errors.name;
}
Update
I'm talking about this section of your angular code, specifically the case in the success callback where data.success is falsey:
$scope.submitForm = function() {
$http({
method : 'POST',
// ...
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errors = data.errors;
$scope.submission = true; //shows the error message
} else {
// ...
}
});
};
Since you're probably binding to e.g. {{ errorName }} in your view template, wherever that is, that will also have to be updated with what I have above if you switch your $error array to return with numerical indices.

Related

php not working correctly on the enquiry/callback form but works fine on the contact form

This is confusing me any ideas as to why I only receive the telephone number (missing the name and email fields) when a form is submitted? Ive tried changing everything but i can't seem to get the other 2 fields to work when submitted.
<aside class="sidebar">
<h3 class="text-center">Request a Callback</h3>
<div class="enquiry-wrapper">
<form id="enquiry-form" method="post" action="enquiry.php" class="clearfix">
<input type="text" name="enquiry-name" id="enquiry-name" autocomplete="off" placeholder="Name ...">
<input type="email" name="enquiry-email" id="enquiry-email" autocomplete="off" placeholder="Email ...">
<input type="tel" name="tel" id="tel" autocomplete="off" placeholder="Phone Number ...">
<div class="form-submit">
<input type="submit" class="btn btn-colour" name="enquiry-submit" id="enquiry-submit" value="Send message">
</div>
<!-- form-submit end -->
</form>
<div id="enquiry-message"></div>
</div>
<!-- enquiry-wrapper end -->
</aside>
This is the enquiry.php
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'contact#rpsfm.co.uk';
// an email address that will receive the email with the output of the form
$sendTo = 'contact#rpsfm.co.uk';
// subject of the email
$subject = 'new contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('enquiry-name' => 'Name', 'enquiry-email' => 'Email', 'tel' => 'Tel');
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
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 just display the message
else {
echo $responseArray['message'];
}
?>
This is the js.
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function() {
var e = $(this).attr("action");
$("#enquiry-message").slideUp(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
name: $("#enquiry-name").val(),
email: $("#enquiry-email").val(),
tel: $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove()
});
$("#enquiry-submit").removeAttr("disabled");
if (e.match("success") != null)
$("#enquiry-form").slideUp("slow")
})
});
return false
})
});
Hope I've done this right if not let me know any more info you need.
ATB
Luke
there are multiple things which make me wonder, besides that I do not understand what you are trying to accomplish.
In enquiry.php:
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
Taken this excerp from the manual:
The second special case is the "Location:" header. Not only does it
send this header back to the browser, but it also returns a REDIRECT
(302) status code to the browser unless the 201 or a 3xx status code
has already been set.
By passing this to a variable you are redirecting almost instantly before executing your code.
Secondly your JavaScript code does not seem to work as you desire. I think you want to send your form via AJAX, but your code is ignored, because the form is send via regular post.
event.preventDefault(); should prevent the sending of the form via regular submit.
Used like
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
// [...]
});
});
I update as I come along with more issues.
Update
Please take a look at this:
$(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
var e = $(this).attr("action");
$("#enquiry-message").slideDown(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
"enquiry-name": $("#enquiry-name").val(),
"enquiry-email": $("#enquiry-email").val(),
"tel": $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove();
});
$("#enquiry-submit").removeAttr("disabled");
if (e.type === "success") {
$("#enquiry-form").slideUp("slow");
}
});
});
});
});
You have used the wrong variable names for the POST data. So your assoc array in the enquiry.php could not use the correct keys and left it out. It seems like the assignment of the header() function works, but it seems like very bad practice to me. You could return the ok message with your AJAX return call, instead of using the header() function.

how to exact output in ajax

My code is working well but problem in output. I don't get exact output that i want.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
console.log(data);
},
error:function(){
console.log("Error: Unknown Error");
}
});
});
PHP code:
<?php
if(isset($_SESSION['userId'])) {
echo "1";
} else {
echo "0";
}
?>
output in success gives also html code, why?
0 </div>
<footer class="nav navbar-inverse">
...........
</footer>
</body>
</html>
I want in my output only 0 in a variable, not html code.
The problem is with your php code here's an example php code. You need to encode as JSON this lets jQuery .success or .fail have a JSON response as a callback.
What I am doing is I have a php file and a js file.
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "me#example.com";
$subject = "Website Contact Form: ".$name;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
$(function() {
$("#contactForm").submit(function(e) {
$.ajax({
type: 'POST',
url: 'contact.php',
data: $(this).serialize(),
dataType: "json"
})
.done(function(msg) {
if (msg.success == true) {
response = '<div class="success">' + msg.message + '</div>';
$contactform.hide();
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Show response message.
$("#contactForm").prepend(response);
})
e.preventDefault();
});
});
Because the php is successful in returning a result.
The error would be triggered if the php failed to return.
If you want your Ajax handler to do something different if not logged in either specify in the Ajax handler (not recommended) or do it on the server side (in the php) returning what you want if they are not authenticated.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
if (data==1){
console.log ("yeah it worked")
}else {
console.log ("error")
}
});
});

PHP Response line break

Yes, I am mentally challenged tonight.
If anyone could help, that'd be very cool.
I just need to add a line break to the php string of a return message after the 'out'.
PHP FILE
// CHANGE THE TWO LINES BELOW
$email_to = "m.wolf#me.com";
$email_subject = "message submission";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
JS FILE
scotchApp.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
I just can't seem to make it work.
terribly entry level, I know.
If it helps: I am using php/angular/bootstrap.
Anyway. thanks.
One way would be using PHP_EOL constant and nl2br function:
<?php
$data['messageSuccess'] = 'Thanks for reaching out'.PHP_EOL.' We will contact you shortly. ';
echo nl2br($data['messageSuccess']);
?>
or using \n :
<?php
$data['messageSuccess'] = "Thanks for reaching out.\n We will contact you shortly.";
echo nl2br($data['messageSuccess']);
?>
If you don't have error reporting enabled, and it seems you don't, you can do it like this:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
Use <br /> or \n to "force" a new line. Or you can wrap your sentence into <p> tags like this:
$data['messageSuccess'] = '<p>Thanks for reaching out.</p> <p>We will contact you shortly. </p>';

Cant get google recaptcha v2 to prevent form submission

So I can successfully get the captcha to validate, using the following code.
</p>
<?php
if(isset($_POST['g-recaptcha-response'])){
echo verify($_POST['g-recaptcha-response']);
}
function verify($response) {
$ip = $_SERVER['blank']; //server Ip
$key="secretkey"; // Secret key
//Build up the url
$url = 'https://www.google.com/recaptcha/api/siteverify';
$full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
//Get the response back decode the json
$data = json_decode(file_get_contents($full_url));
//Return true or false, based on users input
if(isset($data->success) && $data->success == true) {
return True;
}
return False;
}
?>
<p style="text-align: justify;">
<script type="text/javascript">
function verify(){
var serializedValues = jQuery("#infoForm").serialize();
jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
if(result){
$('#show').html('Your Form Successfully Submitted');
$('.formwrap').hide(result);
return true;
}
}});
$('#show').html('Please Enter Valid Captcha');
return false;
}
var onloadCallback = function() {
grecaptcha.render('captcha_ele', {
'sitekey' : 'Enter Your Site Key Here', // Site key
});
};
</script>
However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...
<!-- language: lang-css -->
$("#blank").submit(function() {
$.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'},
function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
<?php
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
$to = 'info#blank'; // Replace with your email
$subject = 'Message from website visitor'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
I use this which works for me. Put a js function in your form submit to validate the re-captcha:
<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">
Then some js to stop the form submit if the user didn't tick the check box:
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("not validated");
return false;
} else {
alert("validated");
return true;
}
}
You can swap out the alerts for toast or as you are doing some elements on the page.
HTH
In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:
jquery('form').on('submit',function(e){
if(grecaptcha.getResponse() === "") {
e.preventDefault();
alert('Error: \n please validate the Captcha test');
}
});
You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.
This is a simpler model that does the job
document.querySelector(".form").addEventListener("submit", (event)=>{
const response = grecaptcha.getResponse();
if (response.length === 0) {
event.preventDefault();
alert("Please verify that you are human!");
}
})
<!--reCAPTCHA v2 -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="/" method="POST" class"form">
<!--Please register as a developer and add "your_site_key" you will find it on https://www.google.com/recaptcha/admin/create-->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>

Ajax form won't display success message

I'm having an issue with an contact form everything works except it will not show the success message after the form is added to the db.
The process script
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'db.php';
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$device = stripslashes($_POST['device']);
$model = stripslashes($_POST['model']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check phone number
if(!$phone)
{
$error .= 'Please enter your phone number.<br />';
}
// Check device
if(!$device)
{
$error .= 'Please enter your device manufacturer.<br />';
}
// Check device model
if(!$model)
{
$error .= 'Please enter your device model.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
// Get current time stampe
$date = time();
if(!$error)
{
$addDB = "INSERT INTO contactus (`name`,`email`,`phone`,`device`,`model`,`subject`,`message`, `date`, `read`) VALUES ('$name','$email','$phone','$device','$model','$subject','$message','$date', '')";
$result = mysqli_query($con,$addDB) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.'</div>';
}
}
And here is the jQuery part
<script type="text/javascript">
$(document).ready(function ()
{ // after loading the DOM
$("#ajax-contacts").submit(function ()
{
// this points to our form
var str = $(this).serialize(); // Serialize the data for the POST-request
$.ajax(
{
type: "POST",
url: 'includes/contact-process.php',
data: str,
success: function (msg)
{
$("#note").ajaxComplete(function (event, request, settings)
{
if (msg == 'OK')
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
Thanks any help is gladly appreciated.
Drop this line:
$("#note").ajaxComplete(function (event, request, settings)
You don't need it as you are already in the success: function.
For debugging purpose you can try to put in an alert("Test"); just above that troublesome line to check if it is displayed.
Note that the success callbacks have been deprecated and you should instead use .done. See the jQuery API for more info:
You could also try and do some debugging yourself. E.g. Chrome has some really good developer tools where you can see a lot of stuff and you can even setup breakpoints and walk through your code step-by-step. Very useful.
Hit F12 to show Developer Tools.
Go in to Settings:
Enable logging of XHR/Ajax requests:
When doing Ajax requests hereafter it will be logged in the console:
Just rightclick on that Ajax request to trigger a new identical request. In this way you can see exactly what the browser sends and what your PHP script receives. Of course the request needs to be GET for you to debug the variables being passed.

Categories