I have a contact form in my index page that should have the email and message of visitor which will be stored in mysql table after send button is clicked , I've created a jquery button click function which has the ajax call and ajax request goes to a page called contact I don't know why it's not working did I missed up ! now This is my project structure:
index.php
connect.php (Database Connection)
js (folder) => ajax.js (The jquery file inside the "js" folder)
ajax (folder) => contact.php (The php file inside the ajax folder)
My html:
<div id="index-contact-form">
<form>
<div>
<input type="email" id="con-email" required>
<label>Email</label>
</div>
<div>
<textarea id="con-msg" required></textarea>
<label>Message</label>
</div>
<div>
<button id="con-send-btn" class="btn index-contact-form-btn">Send</button>
<p id="con-error"></p>
</div>
</form>
</div>
This is my ajax.js file code:
$(document).ready(function(){
$("#con-send-btn").click(function(e){
e.prvenetDefault();
// Get Vister Entered Data
var contactEmail = $("#con-email").val().trim();
var contactMsg = $("#con-msg").val().trim();
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "../ajax/contact.php",
type: "POST",
data: {email:contactEmail,message:contactMsg},
dataType:"json",
success: function(data){
$("#index-contact-form").empty();
$("#index-contact-form").append(data.success);
},
error: function(data){
$("#con-error").text(data.fail);
}
});
});
});
This is my contact.php file code:
<?php
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include("../connect.php");
if(isset($_POST['email']) && isset($_POST['message']))
{
// Get Data From POST Request
$email = $_POST['email'];
$message = $_POST['message'];
// Declare Variables For Maintain The Results
$success = '';
$fail = '';
// Validate The Form
$formErrors=array(); // Empty Array Defined For Containing Error Messages Of Empty Inputs
if(isset($email))
{
$filteredEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
if(filter_var($filteredEmail , FILTER_SANITIZE_EMAIL) != true)
{
$formErrors[]='Email not valid';
}
if(strlen($filteredEmail) > 100)
{
$formErrors[]='Email should be less than 100 characters';
}
if(empty($filteredEmail))
{
$formErrors[]='You should provide email';
}
}
if(isset($message))
{
$filteredMessage = filter_var($message,FILTER_SANITIZE_STRING);
if(strlen($filteredMessage) < 10)
{
$formErrors[]='Message can't be less than 10 characters';
}
if(strlen($filteredMessage) > 255)
{
$formErrors[]='Message must be less than 255 characters';
}
if(empty($filteredMessage))
{
$formErrors[]='Message must not be empty';
}
}
// If There Is No Error Procced The Insert Operation
if(empty($formErrors))
{
// Insert User Info In Database
$stmt = $con->prepare("insert into contact (ID , email , message) values (DEFAULT , :cemail , :cmessage)");
$stmt-> execute(array(
'cemail' => $email,
'cmessage' => $message
));
$success .= "Message has been sent";
}
else
{
foreach($formErrors as $error)
{
$fail .= $error;
}
}
$data = array('success' => $success,'fail' => $fail);
echo json_encode($data);
}
?>
Related
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.
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")
}
});
});
I am new in HTML and PHP, I have created a contact form for the users where they can add their messages. When they click on the send button I want the page to stay on this contact form and show a text message below that says it is succesfully sent. Here is my code some of it .
if (isset($_POST['submit']))
{
if (!isset($_POST['name'])) {
echo "please enter the name";
}else {
if (!isset($_POST["emailaddress"])) {
echo "please enter the email adresse ";
}else {
if (!isset($_POST["subject"])) {
echo " Please enter the message ";
} else {
$nom = $_POST['name'];
$email = $_POST['emailaddress'];
$msg = $_POST['subject'];
$sql = "INSERT INTO contacts (name, email, message) VALUES ('$nom', '$email', '$msg') ";
if (!mysql_query($sql)){
die ('error : ' . mysql_error());
} else {
mysql_close($link);
?>
</br></br>
<p25><center>sent succesfully! thanks</center></p25>s
<?php
echo "<script>setTimeout(\"location.href = 'no-sidebar.php'\",8000);</script>";
You need to understand each line of code.
if (!isset($_POST['name'])) {
echo "please enter the name";
}
The page will get reloaded on the first instance.
You need to do the form validation part in javascript. In this way, if some validation error happens, it can be displayed somewhere in the page without reloading it.
Then send the data to php through ajax, where you set your model and pass it to database and send a response back to javascript which can then print the message that the form has been submitted successfully.
Here's what I'm saying:
<input type="text" id="email" />
<button id="submit">Submit</button>
<div id="status"></div>
Javascript Part:
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
if(email.trim().length === 0){
$('#status').html('Email not provided');
}else{
$.ajax({
type : 'POST',
data : {action: 'sendData' , email : email}, // object
url : 'example.php',
cache: false,
success: function(response){
$('#status').html(response);
}
});
}
});
});
And in the php side, then you can just get the value which is already validated and return true or false based on your data insertion result to database.
example.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'sendData'){
$email = $_POST['email'];
if(dbinsertion successful){
echo "Success";
}else{
echo "Something went wrong";
}
}
?>
You have to use jquery here. Hope you understood.
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.
I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.