The code is this. It's not responding. JavaScript.
Am trying to do a contact form.
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
jQuery.ajax({
url: "contact.php",
data:'name='+$("#name").val()+'&email='+$("#email").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
}
The php file is
<?php
include_once "config.php";
$name = validate($_POST["name"]);
$email = validate($_POST["email"]);
$message = validate($_POST["message"]);
$subject = validate($_POST["subject"]);
$to = 'myemail#example.com';
$mailHeaders = "From: " . $name . "<" . $email . ">\r\n";
if (mail($to, $subject, $message, $mailHeaders)) {
print "<p class='success'>Contact Mail Sent.</p>";
} else {
print "<p class='Error'>Problem in Sending Mail.</p>";
}
function validate($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Related
Hi i have been trying for a good 2 hours to get this dropdown menu to get the selected result to go to email through post method im new to php and i think i could just do with abit of guidance ill post html php js code below.i have tried many ways this isnt my only edit ive literally tried everything i just need a little help
html
<div class="col-lg-3">
<div class="form-group mt-2">
<div class="dropdown" >
<select name="vehicles" id="vehicles" class="ddstyle">
<option value="motor" selected>Motorcycle</option>
<option value="Car">Car</option>
<option value="Small">Small Van</option>
<option value="Opel">Opel</option>
<option value="Midi">Midi Van</option>
<option value="SWB">SWB up to 2.4m</option>
<option value="MWB3">MWB up to 3m</option>
<option value="LWB4">LWB up to 4m</option>
<option value="XLWB4">XLWB 4m+</option>
<option value="Luton">Luton</option>
<option value="T5">7.5T</option>
</select>
</div>
</div>
</div>
PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$dod = $_POST['dod'];
$yourname = $_POST['yourname'];
$tel = $_POST['tel'];
$caddy = $_POST['caddy'];
$cpost = $_POST['cpost'];
$daddy = $_POST['daddy'];
$dpost = $_POST['dpost'];
$dofd = $_POST['dofd'];
$Car = $_POST['Car'];
$Small = $_POST['Small'];
$Opel = $_POST['Opel'];
$Midi = $_POST['Midi'];
$MWB = $_POST['MWB'];
$MWB3 = $_POST['MWB3'];
$LWB4 = $_POST['LWB4'];
$XLWB4 = $_POST['XLWB4'];
$Luton = $_POST['Luton'];
$T5 = $_POST['T5'];
//*$vehicles = $_POST['$vehicles'];**/
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
if(isset($_POST['vehicles']) && $_POST['vehicles']=='motor') echo $value;
if(trim($name) == '') {
echo '<div class="error_msg">You must enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_msg">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_msg">You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($dod) == '') {
echo '<div class="error_msg">Please enter your collection date.</div>';
exit();
}
if(trim($dofd) == '') {
echo '<div class="error_msg">Please enter your drop off deadline.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#example.net";
$address = "admin#ready2gologistics.co.uk";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = ' ' . $name . ' has a possible job!';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "$name wants a quote details are listed below." . PHP_EOL . PHP_EOL;
$e_content =
"
Company: $name
Name of Person: $yourname
Contacts email: $email
Contacts Telephone Number: $tel
Desired Collection Date: $dod
Drop Off Deadline: $dofd
Collection Address: $caddy
Collection Post Code: $cpost
Destination Address: $daddy
Destination Post Code: $dpost
Addtional Information: $comments
test: $value
" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_msg'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your quote has been submitted to us. To see how we use your information check out our <a href='PrivacyPolicy.html".$link_address."'>Privacy Policy</a></p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
JavaScript
//Contact
$('#working_form').submit(function() {
var action = $(this).attr('action');
$("#message").slideUp(750, function() {
$('#message').hide();
$('#submit')
.before('<img src="" class="gif_loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
dod: $('#dod').val(),
dofd: $('#dofd').val(),
yourname: $('#yourname').val(),
cpost: $('#cpost').val(),
caddy: $('#caddy').val(),
tel: $('#tel').val(),
daddy: $('#daddy').val(),
dpost: $('#dpost').val(),
vehicles: $('#vehicles').val(),
value: $('#value').val(),
},
function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.gif_loader').fadeOut('slow', function() {
$(this).remove()
});
$('#submit').removeAttr('disabled');
if (data.match('success') != null) $('#cform').slideUp('slow');
}
);
});
return false;
});
In $.post request pass send value
$.post(action, {
...other data
value: $('#value').val(),
send: $('#send').val(),
}
Because your $value vehicle data is depended on if(isset($_POST['send'])) check
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
I apologize for not providing the full code for context, I am VERY new to this. Here is the code for the signup.php file:
<?php
session_start();
include('connection.php');
$missingUsername='<p><strong>Please enter a username</strong></p>';
$missingEmail='<p><strong>Please enter your email address</strong></p>';
$InvalidEmail='<p><strong>Please enter a valid email address</strong></p>';
$missingPassword='<p><strong>Please enter a password</strong></p>';
$InvalidPassword='<p><strong>Your password should be at least 6 characters long and include one capital letter and one number</strong></p>';
$differentPassword='<p><strong>Passwords don\'t match</strong></p>';
$missingPassword2='<p><strong>Please confirm your password</strong></p>';
if(empty($_POST["username"])){
$errors .= $missingUsername;
}else{
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
}
if(empty($_POST["email"])){
$errors .= $missingEmail;
}else{
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors .= $InvalidEmail;
}
}
if(empty($_POST["password"])){
$errors .= $missingPassword;
}elseif(!(strlen($_POST["password"])>6 and preg_match('/[A-Z]/',$_POST["password"]) and preg_match('/[0-9]/',$_POST["password"]))){
$errors .= $InvalidPassword;
}else{
$password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
if(empty($_POST["password2"])){
$errors .= $missingPassword2;
}else{
$password2 = filter_var($_POST["password2"], FILTER_SANITIZE_STRING);
if($password !== $password2){
$errors .= $differentPassword;
}
}
}
if($errors){
$resultMessage = '<div class="alert alert-danger">' . $errors .'</div>'
echo $resultMessage;
}
$username = mysqli_real_escape_string($link, $username);
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$password = hash('sha256', $password);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
$results = mysqli_num_rows($result);
if($results){
echo '<div class="alert alert-danger">That username is already registered. Do you want to log in?</div>';
exit;
}
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
$results = mysqli_num_rows($result);
if($results){
echo '<div class="alert alert-danger">That email is already registered. Do you want to log in?</div>';
exit;
}
$activationKey = bin2hex(openssl_random_pseudo_bytes(16));
$sql = "INSERT INTO users ('username', 'email', 'password', 'activation') VALUES ('$username', '$email', '$password', '$activationKey')";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">There was an error inserting the user details in the database!</div>';
exit;
}
$message = "Please click on this link to activate your account:\n\n";
$message .= "http://studenttest.host20.uk/activate.php?email=" . urlencode($email) . "&key=$activationKey";
if(mail($email, 'Confirm your Registration', $message, 'From:'.'msyed0230#gmail.com')){
echo "<div class='alert alert-success'>Thank you for registration! Confirmation email has been sent to $email. Please click on the activation link to activate your account.</div>";
}
?>
Here again is the JS code block I'm working with within a broad goal of making a proper sign-up form:
$("#signupform").submit(function(event){
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signup.php",
type: "POST",
data: datatopost,
success: function(data){
if(data){
$("#signupmessage").html(data);
}
},
error: function(){
$("#signupmessage").html("<div class='alert alert-danger'>There was an error with the Ajax call. Please try again later.</div>");
}
});
});
For some reason, I keep getting the AJAX error instead of the typical error messages I set up for username entry, password entry, etc. It is linked to the correct files (put in the script tag in my main index.php file) and with everything else.
What could be going on?
You might have an error in your signup.php page so it would be better if you put the whole code so as to find the issue and to fix it.
I've made a little example with almost the same code as yours and it works fine :
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" >
<div id="signupmessage"></div>
<form id="signupform" action="" method="POST">
<input type="text" name="firstname" placeholder="Enter your first name" /><br /><br />
<input type="text" name="lastname" placeholder="Enter your last name" /><br /><br />
<input type="submit" value="submit">
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
$("#signupform").submit(function(event){
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signup.php",
type: "POST",
data: datatopost,
success: function(data){
$("#signupmessage").html(data);
},
error: function(data){
$("#signupmessage").html(data);
}
});
});
</script>
--------- signup.php -----------
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname."<br />";
echo $lastname;
}
else{
echo "<div class='alert alert-danger'>There was an error with the Ajax call. Please try again later.</div>";
}
?>
My jquery ajax is not submitting form to my php file. The success alert only alert blank on submit and it won't insert anything to my database. But my php file inserts to database without using ajax.
Here is my code, any idea or new way to do this
This is the AJAX CODE
$(document).ready(function(){
alert("mannn");
$("#adduser").submit(function(){
$.ajax({
type: "POST",
url: "adduser_processor.php",
data: $('#adduser').serialize(),
success: function(data){
alert(data);
}
Here is the php code to insert to database
if (isset($_POST['submit'])) {
//Check if the form is submitted
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$gender = $_POST['gender'];
$about = $_POST['about'];
$number = $_POST['number'];
$password = $_POST['password'];
$timeadded = date("Y/m/d, \a\\t G.ia ( l)");
$address = $_POST['address'];
// Wanna Clean Values to prevent fro Hackers
$fullname = cleaninputs($fullname);
$username = cleaninputs($username);
$about = cleaninputs($about);
$number = cleaninputs($number);
$gender = cleaninputs($gender);
$password = cleaninputs($password);
$address = cleaninputs($address);
$checkuserq = "SELECT username FROM pos_staffs WHERE username = '$username'";
$exeq = mysqli_query($connection, $checkuserq);
$numrow = mysqli_num_rows($exeq);
if ($numrow > 0) {
$msg = "<li class='list-group-item list-group-item-danger'>Username ($username) Choosen by Another Staff</li>";
//echo $msg;
//header("location:addnewuser.php?msg=$msg");
} else {
$insertquery = "INSERT INTO pos_staffs(id,fullname,username,password,about,gender,address,date_joined)
VALUES('','$fullname','$username','$password','$about','$gender','$address','$timeadded')";
$insertq = mysqli_query($connection, $insertquery);
if ($insertq) {
//header("location:addnewuser.php?msg=$msg");
$msg = "New Staff ($fullname) has being added he can now Login";
echo $msg;
} else {
$msg = "Something Went Wrong";
echo $msg;
}
But i dont think my php file has an error because it insert normally without error.
The script below helps with processing of a form that request number and name values, and than sends it to process.php and also displays a confirmation and hides the button that would fired the modal to the form so user cannot retry to fill the form.
Script to handle pass data to process.php
$(document).ready(function () {
function successHandler(){
console.log('Success');
$("#thanks").html(msg);
$('#form-content').modal('hide');
}
function errorHandler(){
console.log('Error');
alert("Error");
}
var nameval = $('#name').val();
var numberval = $('#number').val();
$("form#contact").submit(function(){
$.ajax({
type: "POST",
url: "process.php",
data: {
name: nameval,
number: numberval,
submit: true
},
success: function(msg){
$("#thanks").html(msg);
$('#form-content').modal('hide');
return false;
},
error: function(){
alert("Error");
return false;
}
});
return false;
});
});
The whole action does generate an email with HTML from the process.php script but does not include the data that was captured from the form, I believe there is a error within this script as I cannot find anything on the form or process.php that is using PHPMail() doing anything wrong.
Could you help?
Update
<?php
if (isset($_POST['submit'])) {
$name = ($_POST['name']);
$number = ($_POST['number']);
echo "<span class=\"alert alert-success\">THANKS! SUBMITTED</span>";
$to = "EMAIL BLANKED";
$subject = "Alert!";
$message = "name: $name number: $number";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <email blank>' . "\r\n";
mail($to,$subject,$message,$headers);
}
else { echo '<div class="alert alert-error">Error</div>' ; }
?>
You should put this two lines:
var nameval = $('#name').val();
var numberval = $('#number').val();
inside the submit function like this
$("form#contact").submit(function(){
var nameval = $('#name').val();
var numberval = $('#number').val();
because if you set the values of the variables before the submission of the form the inputs will most likely be empty.
I've tested my site's mailing with a different script - just to make sure it wasn't the host, and it's working fine.
I'm not sure why my code isn't working. I've included all my contact forums code except the html. It seems to not be loading the php, as it doesn't show any error messages when I put in an invalid email etc. - it just refreshes the page it seems.
Help is much appreciated, thanks everyone.
<!-- Contact Form Js -->
<script type="text/javascript">
// contact form js
jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "inc/contact-process.php",
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
setTimeout("location.reload(true);",7000);
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
});
</script>
<!-- End Contact -->
PHP - 'contact-processes'
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$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 message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
if(!$error)
{
ini_set("sendmail_from", WEBMASTER_EMAIL); // for windows server
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
PHP - 'functions'
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
PHP - 'config'
<?php
define("WEBMASTER_EMAIL", 'snip#myemail.com');
?>