I have problem with pop up form . It doesn't send email. Here is html form:
<form action="#" method="post" id="form" >
<img src="images/3.png" id="close"/>
<h2>Contact Us</h2><hr/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<textarea name="message" placeholder="Message" id="msg"></textarea>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
JS to pop up html form:
function check_empty(){
if(document.getElementById('name').value == ""
|| document.getElementById('email').value == ""
||document.getElementById('msg').value == "" ){
alert ("Fill All Fields !");
}
else {
document.getElementById('form').submit();
alert ("Form submitted successfully...");
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
And php function to send form data to email. Everything work but i don't receive email on gmail. Similar php script i used to post email without pop up and it worked.
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['name'];
$message = $first_name . " wrote following:" . "\n\n" . $_POST['message'];
mail($to,$from,$message);
}
?>
Simple: You don't have an element named "submit" in your form, so your if() test always fails.
id != name in HTML forms; meaning, id does not equal name.
A simple work around:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted ...
}
But this code is bad in any case. You should NEVER use only client-side validation. It's too easy to bypass. ALWAYS validate/verify on the server as well.
You should set your action in the form to the URL of your action in the server.
Related
Uncaught ReferenceError: ajaxObj is not definednewsletter #
main.js:22onclick # index.php:541
I am trying to develop a newsletter which will be on the footer part of the every page and it will use NAME and EMAIL to suscribe. It will grab the data entered by user from HTML form and pass it to ajax for validation after usere click submit which will pass information to newsletter.php and give back message to user if they already exist or signup sucessfull message but what happened is as User click submit button it just says "Please wait.." and keeps on loading forever giving above message on chrome cousole.
I want user to be able to sign up from any page they are on without reloading page.
The problem here is
Above Error given in Chrome cousole while I try to submit the form.
Thank you for looking at my problem. Any help will be appriciated..
HTML
<?php include_once('newsletter.php'); ?>
<form name="signupform" id="signupform" method="POST" onsubmit="return false;">
<p align="center"><strong>NEWSLETTER SIGNUP :</strong>
<input id="sus_name" name="sus_name" type="text" placeholder="Enter your Name" size="15">
<input id="sus_email" name="sus_email" type="text" placeholder="Enter your Email" size="26">
<input id="optin" name="optin" type="submit" value="SUBSCRIBE" onclick="newsletter()"><br>
<span id="status"></span>
</p>
</form>
AJAX
//News Letter Validation
function newsletter(){
var u = document.getElementById("sus_name").value;
var e = document.getElementById("sus_email").value;
var m =(document.URL);
var status = document.getElementById("status");
if(u == "" || e == ""){
status.innerHTML = "Fill out all of the form data";
} else {
document.getElementById("optin").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST","(document.URL)");//Problem with this line as i want it to post to same page where url will be dynamic
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
document.getElementById("optin").style.display = "block";
} else {
window.scrollTo(0,0);
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> ";
}
}
}
ajax.send("u="+u+"&e="+e);
}
}
newsletter.php
<?php
$msg_to_user = "";
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once "includes/mysqli_connect.php";
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = ereg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// GET USER IP ADDRESS
$ip = ereg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if (($u != "") && ($e != "") ){
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $u;
$email = $e;
$sql = mysql_query("SELECT * FROM news_letter WHERE susc_email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Please type an email address ' . $name . '.</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">' . $email . ' is already in the system.</font></h4>';
} else {
$i= substr($name,0,3);
$j=rand(1000,9999);
$l= substr($email,0,3);
$k= $i.$j.$l;
$o=rand(0,9);
$m=str_replace("#","$o","$k");
$n=mysql_real_escape_string($m);
$sql_insert = mysql_query("INSERT INTO news_letter (susc_name, susc_email, susc_date, susc_code)
VALUES('$name','$email',now(),'$n')") or die (mysql_error());
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
echo "signup_success";
exit();
}
}
}
?>
I have a contact form with a captha in it. There is no problem submitting mail, but the issue I have is validation and transferring the values to submit handler. I have limited knowledge of PHP and Javascript. I humbly seek your help in checking these codes and tell me what I need to do to get it right. Any help will be appreciated!
Below are the mail handler php codes
<?php
require_once('recaptchalib.php');
$publickey = "***********";
$subject = 'CONTACT MESSAGE: ' ; //. $_REQUEST['subject']Subject of your email
$to = 'myemailaddress#domain.com'; //Recipient's E-mail
$privatekey = "***********";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message .= 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Telephone: ' . $_REQUEST['telephone'] . "<br>";
$message .= 'Email: ' . $_REQUEST['email'] . "<br>";
$message .= 'Message: ' . $_REQUEST['message'];
if (#mail($to, $subject, $message, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sent';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
} else {
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error;
}
?>
And here is the javascript
<script>
function validateForm() {
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
return false;
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
return false;
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
return false;
}
// If there is no validation error, next to process the mail function
if(error == false){
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
}else{
//Display the error message
}
});
}
}
</script>
and finally, the html
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
<label> <input name="name" type="text" id="name" style="width: 90%;" placeholder="Name" ></label>
<label><input name="email" type="text" id="email" style="width: 90%;" placeholder="Email"></label>
<label><textarea name="message" id="message" style="width: 96.5%;" class="mssg" rows="10" placeholder="Message"></textarea>
</label>
<label><?php echo recaptcha_get_html($publickey) ?></label>
<label><input name="submit" type='submit' id='mssg_buttton' value='Send Message'></label>
</form>
When I clicked on the submit button, I was taken straight to
processContactEmail.php page without the form validating
How do I display this error: echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error; in my alert
I'm not sure about this line if(error == false){ in the JS script since there is no variable declared
The first problem looks like your validation function is referred to in your HTML as validate();
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
But in your Javascript the function defined is called validateForm(). To fix that just make sure these are called the same thing (doesn't matter what, as long as they match).
Rather than calling the validation function inline with onSubmit="return validate();" , it's better to attach a separate event listener in the Javascript. It's good practice to separate your HTML and Javascript code. I see you're using JQuery, so you do this in your Javascript like so:
$( document ).ready(function() { // Make sure DOM is loaded before attaching the event listener to the form element
$("#enquiries").on("submit", validateForm); // Add submit listener to the form with the id 'enquiries' and run the function called validateForm on submit
});
Secondly, in your validate function, you need to prevent the form's default action of submitting and redirecting to the action processContactEmail.php. The HTML form will always try to post to its default action, so do make it do something else (like validate) you must actively stop it from posting.
You do this in JQuery by editing your validateForm function to prevent the form's default action with event.preventDefault. As for the error, you must first set an error variable to false (assume all is fine) and as you find errors, you change it to true. If it's still false after the checks, there were no errors.
Your Javascript function should look like this:
function validateForm(event) {
event.preventDefault(); // the variable "event" is automatically included in the submit event listener.
var error = false; // Assume it's fine unless proven otherwise
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
error = true; // The form is not fine. Set error to true.
// No return, or you will not get to the rest of your function
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
error = true; // The form is not fine. Set error to true.
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
error = true; // The form is not fine. Set error to true.
}
// If there is no validation error, next to process the mail function
if(error == false){ // error was never set to true, so it must still be false and the form is OK.
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php */
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
} else {
//Display the error message
}
});
}
}
After these changes, your form will not post to its action, and your validateForm function should run, check for the errors, and if there are none, make the ajax POST to processContactEmail.php.
I have 3 files:
1. Simple form with email and password
2. login_validate.php to validate form input against database
3. login.js to perform ajax task
I tried to validate form with just login_validate.php and everything worked for me. But when i tried to use ajax(login.js), it always tells me wrong email and password even I tried to type in correct email and password in form. Below is my code, please advice what is wrong with it?
Here is my form:
<div id="login_result"></div>
<form action="login_validate.php" method="post">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<input type="password" class="form-control" id="pass" name="pass" placeholder="Password">
<button type="submit" class="btn btn-default" name="submit" id="submit">Submit</button>
</form>
Here is my login_validate.php:
<?php
require("configs/dbconnect.php");
if(isset($_POST["dangnhap"])){
$email=mysql_real_escape_string($_POST["email"]);
$pass=mysql_real_escape_string($_POST["pass"]);
$sql = 'SELECT name, email, pass, visible FROM user WHERE email = "'.$email.'" AND pass = "'.$pass.'"';
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num_rows= mysql_num_rows($result); // Get the number of rows
if($num_rows > 0){
$row = mysql_fetch_array($result);
echo 1;
$_SESSION["email"]=$row["email"];
$_SESSION["pass"]=$row["pass"];
$_SESSION["name"]=$row["name"];
}
else{
echo 0;
}
}
?>
Here is my login.js:
$(document).ready(function(){
$('#email').focus(); // Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var email = $('#email'); // Get the username field
var pass = $('#pass'); // Get the password field
var login_result = $('#login_result'); // Get the login result div
login_result.html('loading..'); // Set the pre-loader can be an animation
if(email.val() == ''){ // Check the username values is empty or not
email.focus(); // focus to the filed
login_result.html('<span class="error">Enter the username</span>');
return false;
}
if(pass.val() == ''){ // Check the password values is empty or not
pass.focus();
login_result.html('<span class="error">Enter the password</span>');
return false;
}
if(email.val() != '' && pass.val() != ''){ // Check the username and password values is not empty and make the ajax request
var UrlToPass = 'email='+email.val()+'&pass='+pass.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
cache: false,
data : UrlToPass,
url : 'login_validate.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">Username or Password Incorrect!</span>');
}
else if(responseText == 1){
window.location = 'member/';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});
No need to test the dangnhap.
in PHP remove the check:
isset($_POST["dangnhap"]) //remove it, no checking for submit required. done in JS file.
Change in JS:
var UrlToPass = {email:email.val(),pass:pass.val()} ;
in HTML:
remove the type( type="submit" ) attribute as you are using <button>
in login_validate.php
if(isset($_POST["dangnhap"])){
but in login.js dangnhap is not set.
in $.ajax({ data can be an object, you dont have to make it a string
In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/
I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.