I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.
html:
<?php
include('ajaxreturn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<body>
<form id="submit" onsubmit="submitForm(); return false;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="Name">Name</label>
<input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
<span class="text-danger"><?php echo $name_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="subject">Subject</label>
<input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
<span class="text-danger"><?php echo $subject_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control pt-0 pb-0" id="category">
<option>...</option>
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-1
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>
</div>
div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-2
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>
</div>
<div class="row">
<button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
</div>
</form>
<!-- Optional JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- <script src="main.js"></script> -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
php:
<?php
// Form Variables
$name = "";
$subject = "";
$category = "";
$classroom="";
//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Your Name";
} else {
$name = validation($_POST["name"]);
// Function calling and checking the letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Your name must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Your Subject";
} else {
$website = validation($_POST["subject"]);
// Function calling and checking the letters and whitespace
if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
$subject_error = "Subjets must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["category"])) {
$category_error = "Please select categoy";
} else {
$category = validation($_POST["category"]);
}
if (empty($_POST["classroom"])) {
$classroom_error = "Select the Class Room";
} else {
$classroom = validation($_POST["classroom"]);
}
}
function validation($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Ajax:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "name", _("name").value );
formdata.append( "subject", _("subject").value );
formdata.append( "category", _("category").value );
formdata.append( "classroom", _("classroom").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "ajaxreturn.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
Error:
ajaxform.php?name=&website=&submit=submit:78 Uncaught TypeError: Cannot read property 'value' of null
at submitForm (ajaxform.php?name=&website=&submit=submit:78)
at HTMLButtonElement.onclick (ajaxform.php?name=&website=&submit=submit:58)
submitForm # ajaxform.php?name=&website=&submit=submit:78
onclick # ajaxform.php?name=&website=&submit=submit:58
ajaxform.php?name=&website=&submit=submit:78
formdata.append( "category", _("category").value );
onclick # ajaxform.php?name=&website=&submit=submit:58
<button name="submit" id="submit" onclick="submitForm()" value="submit" type="submit" class="btn btn-success">submit</button>
Category with Select options Tag
<option value=1>1</option>
<option value=1>1</option>
<option value=1>1</option><option value=1>1</option>
Trying changing the ajax inside to this.
if (this.status == 200 && this.readyState == 4) {
this.responseText;
The rest of your code above looks right. I have never seen xmlhttprequest used having a variable name inside, Usually it looks like
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "ajaxreturn.php", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
I dont know enough php to take a look at your server side validation. I use NodeJs for all of that. Did you console log your this.responseText to see what variable your server is sending back. Also don't have your submit button submit, that is also your problem, have it run the onSubmit function. So...
<button id="submit" name="submit" onclick="submitForm()" class="btn btn-success">submit</button>
and take the onSubmit off of your form tag. I believe this will fix your issues.
When you submit the form, thats what opens a new page, when you just run the function with ajax, that won't make the browser open a new page. It just happens in the background.
Related
I'm making a registration form where you can write a custom security question. If this one is selected, when an error occurs (e.g wrong pass) it should reshow the field. But it does not do that.
This is the field:
<div id="ifYes" style="display: none">
<div class="input-group mb-3">
<input
type="text"
class="form-control"
placeholder="Custom security question"
name="SEC1Q"
onchange="DefaultCheck(this);"
/>
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
</div>
This is how the field gets shown:
<select class="form-control <?php if($q1Empty == true) echo 'is-invalid'; ?>" onchange="QuestionCheck1(this);" name="Q1">
function QuestionCheck1(that) {
if (that.value == "other") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
$(that).removeClass("form-control is-invalid");
$(that).addClass("form-control");
}
I've tried this:
<?php
echo "prepq1();";
?>
unction prepq1() {
document.getElementById("ifYes").style.display = "block";
}
Thanks in advance
I have no idea why people said this has nothing to do with php or that ajax or a form should be used in this matter while a form is already used?
This was my solution may anyone bump into this with a similar issue:
<?php
if($q1 == "other") $style = "display: block;"; // if question 1 is custom
else $style = "display: none;";
?>
<div id="ifYes" style="<?php echo $style; ?>">
I am a novice developer and for some reason I have never been able to get a php contact form to function properly. I've tried templates from bootstrapious and reusable forms but I've never been able to get them to work. My ultimate goal is to have a form with recaptcha but I can't get just a regular old form to work. Here are the codes from my latest attempt. I've been working on this for days and I feel like I'm missing something small and stupid. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Contact form Tutorial from Bootstrapious.com</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>
<p class="lead">This file uses PHPMailer to send the emails.</p>
<form id="contact-form" method="post" action="contact-2.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" 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">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> These fields are required. Contact form template by Bootstrapious.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="contact-2.js"></script>
</body>
PHP
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'uprightjared#gmail.com';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'uprightjared#gmail.com';
$sendToName = 'Demo contact form';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone',
'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back
to you soon!';
// 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');
$emailTextHtml = "<h1>You have a new message from your contact form</h1>
<hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version
of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// 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'];
}
JS
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact-2.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and
apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-
dismissable"><button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
I've been trying this for awhile. I appreciate your help.
I've a form with two fields. 1- Username. 2- City.
Users can select their cities from the city select options (the cities come from the database).
However, if the user didn't find his/her city, he/she can check the checkbox to enable a text input to enter his/her city (and at the same time the select options will be disable).
The issue is, if the user writes new city, the select options will be disable (this is good), but when the user submits the form a and there was a validation issue (for example: empty username!), the form will go back with the following:
The city select options will be enable !!
The city text input will be disable (with sticky city name that the user entered) !!
So, how can I keep the city name in the text input enable with the value, and make the city select options disable??
This is my code:
<title> Form </title>
<link rel="icon" type="image/png" href="images/icon/anta_ana.png">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<div id="page-wrapper">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$city_name = $_POST['city_name'];
//errors handling :
$error = array();
if(empty($username)) $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please write your name!
</div>";
if($city_name == 'all') $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please selects a city!
</div>";
if(empty($error)) {
include("dbc.php");
$q = "INSERT INTO users (username,
city_name) VALUES
('$username',
'$city_name')";
$r = mysqli_query($dbc, $q);
if($r){
echo "<script>window.open('successfully_registered.php', '_self')</script>";
}
else{
echo "error";
}
}
else{
foreach ($error as $err){
echo $err;
}
}
}
?>
<form action="question.php" method="POST" name="" dir="rtl">
<!-- Userame -->
<div class="form-group">
<label class="control-label" style="float: right;"> Username </label>
<input type="text" class="form-control" placeholder="Username" name="username" value =
<?php if(isset($_POST['username'])) echo $_POST['username'] ?>>
</div>
<!-- City -->
<div class="form-group">
<label style="float: right;">City </label>
<?php
include("dbc.php");
$qm = "SELECT DISTINCT city_name FROM cities ORDER BY city_name";
$rm = mysqli_query($dbc,$qm);
while ($row = mysqli_fetch_array($rm)){
$cities_array[] = $row['city_name'];
}
echo '<select class="form-control border-input" name="city_name" id="city_name">';
echo '<option value="all"> All </option>';
foreach($cities_array as $cities){
$selected = '';
if($_POST['city_name'] == $cities) {
$selected = 'selected="selected"';
}
echo '<option value="'.$cities.'"'.$selected.'>'.$cities.'</option>';
}
echo '</select>';
?>
</div>
<!-- Another City? -->
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value =
"<?php if (isset($_POST['new_city'])) echo $_POST['new_city']; ?>" >
<script>
document.getElementById('another_city').onchange = function() {
document.getElementById('new_city').disabled = !this.checked;
if(document.getElementById('new_city').disabled){
$("#city_name").prop('disabled', false);
}
else{
$("#city_name").prop('disabled', true);
}
};
</script>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info btn-fill form-control" name="submit" value="Send"><i class="fa fa-paper-plane"></i> Send </button>
</div>
</form>
</div>
if you want to disable Select just use this code
$('select').attr('disabled','disabled');
first of all: your code is (principally) vulnerable to sql injection,
http://php.net/manual/de/security.database.sql-injection.php
second: the reason is fairly simple, you submit your form, check it in the BACKEND and redirect. The reason why option is enabled and textbox disabled is simply because the page is reloaded, and thats your default setting. you could pass a parameter indicating the failure in your url (like err=wrongArgument) or whatever) and disable the options box with javascript in that case.
If the problem only occurs because of validation you can first submit the form details via an ajax request. validate it and if there are no errors then submit them. If you were using jquery then you could do something like
$("#form-id").submit(function(e){
e.preventDefault();
$.ajax({
method: 'POST',
url: 'validate.php',
data: $(this).serialize(),
success: function(res){
if(res == "success") {
$(this).submit();
} else { // error }
},
fail: function(){
// error
}
})
})
one other thing that you could do is if you redirect to the current page after validation fails and pass a query string at the end that denotes that the user checked the checkbox or not. you have to give your checkbox a name for this so it gets submitted over as well when you submit the form.
if(isset($_POST['another_city']) and $_POST['another_city'] == "on") {
// header("Location: ...") redirects the page to the provided location
header("Location: question.php?checked=1"&city=".$city_name);
}
once you do this you will have to add code to check whether the $_GET['checked'] and $_GET['city'] are set or not. if they are set then you can set the provided values in the form using js like:
php:
$checked = "";
$city = "";
if(isset($_GET['checked']) and $_GET['checked'] == 1) {
$checked = "checked";
}
if(isset($_GET['city'])) {
$city= $_GET['city'];
}
html:
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" <?php echo $checked?> id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value = "<?php echo $city; ?>" >
This question already has answers here:
Ajax Contact Form Problems - No email being sent
(2 answers)
Closed 9 years ago.
Sorry for being a noob but I'm trying my best. I've done and read everything I could find and I have never got this to work. Would really appreciate the help. The form id matches in the html and javascript. The PHP is linked in the Javascript and I have the javascript linked in the head of my html. What am I missing? I've tried other codes I found online as well and nothing.. The issue is that no email ever gets sent through. If you hit send the page reloads and thats it.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
</div>
</div>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thanks.
try preventing the default form submission by changing:
$('#contact').submit(function() {
...
to
$('#contact').submit(function(evt) {
evt.preventDefault();
//rest of your js code
and you dont have input elements with id name, email and message as per your posted code. Add those as ids to your input elements
I'm in no way, shape, or form anywhere near as close or experienced as most of you. However, my experience in PHP compared to Javascript is slightly better. So please excuse me, if my code seems mediocre or "newbie."
Anyways, I have a single page with a form with a simple input box and then two checkboxes. I'm working with ajax for the first time, and I was able to get my code to work, in a sense. In my PHP code, I have it run certain things depending on what checkbox is selected. However, with this ajax code (and/or PHP as well), when it executes my code it runs all of my code even if the checkbox is selected or not. I'm here asking if you see what I did wrong:
[index.php -> form code]
<form method="post" class="form-horizontal">
<fieldset>
<!-- Form Name -->
<legend>Enter the tweet URL below to begin using the service.</legend>
<div id="ajaxDiv" class="alert alert-success">We've successfully completed your request, check twitter now. Or, simply click here.</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="url">Tweet URL</label>
<div class="controls">
<input id="url" name="url" type="text" style="height:43px; width:100%; font-size:18px;" placeholder="" class="input-xlarge" required="">
<p class="help-block">The URL of the tweet we are favouriting or retweeting. <span style="font-size:15px;">Example: https://twitter.com/topIess/status/411632658683150336</span></p>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="control-group">
<label class="control-label" for="checkboxes">What would you like for that tweet?</label>
<div class="controls" required="required">
<label class="checkbox" for="checkboxes-0">
<input type="checkbox" style="margin-top:15px;" name="retweet" id="checkboxes-0" value="Retweet">
Retweets
</label>
<label class="checkbox" for="checkboxes-1">
<input type="checkbox" name="favorite" style="margin-top:15px;" id="checkboxes-1" value="Favourite">
Favourites
</label>
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="submit"></label>
<div class="controls">
<button type="submit" onclick="postStuff();" class="btn btn-inverse">Start Process... </button>
</div>
</div>
</fieldset>
</form>
<div id="status"></div>
[index.php -> javascript]
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var fn = document.getElementById("url").value;
var ln = document.getElementById("checkboxes-0").value;
var url = "handle1.php";
var ln1 = document.getElementById("checkboxes-1").value;
var vars = "url="+fn+"&retweet="+ln+"&favorite="+ln1;
hr.open("POST", url+"?x="+nn+"&y="+nn1, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "Processing...";
}
</script>
[handle1.php -> my PHP code]
<?php
/**
* #file
* User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/
require_once('twitteroauth/twitteroauth.php');
$con=mysqli_connect("host","user","","twtid");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM twitter");
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$connection[$row['id']] = new TwitterOAuth('ZG808c0pad0ar7wpgYPmA', 'BWHnOag1aWQtoYRBH5OtsI9m9Ghr3pTuMBo6z4ZNNP8', $row['key'], $row['secret']);
}
/* Create a TwitterOauth object with consumer/user tokens. */
/* $content = $access_token['oauth_token']. " " . $access_token['oauth_token_secret']; */
/* $content = $connection->get("account/verify_credentials"); */
$url1 = parse_url($_POST['url'], PHP_URL_PATH);
$url = explode("/", $url1);
/* If method is set change API call made. Test is called by default. */
$method = 'statuses/retweet/'.$url[3];
$amt = 18;
$sub = rand(1,2);
$amt1 = $amt-$sub-1;
for ($x=1; $x<=$amt; $x++)
{
if($_POST['retweet'] == "Retweet"){
$content = twitteroauth_row($method, $connection[$x]->post($method), $connection[$x]->http_code);
}
if($x == $amt) {
$done = "yes";
}
}
for ($x1=1; $x1<=$amt1; $x1++)
{
if($_POST['favorite'] == "Favourite"){
$content = $connection[$x1]->post('favorites/create', array('id' => $url[3]));
}
}
in your javascript you are posting the value property of your checkboxes, that is the wrong one to use in this situation (as the value of a checkbox is always the same). instead you should be checking if the checked property is true, as that defines if a checkbox is checked or not.