Currently I am able to add a new email address to my newsletter table, however I am struggling with the AJAX part of the query, ie. the validation.
Below is my Signup.php file:
<?php
require_once('required/init.php');
require_once('required/settings.php');
require_once('required/database.php');
require_once('required/class.phpmailer.php');
require_once('required/globals.php');
$email = trim($_REQUEST["email"]);
// Check if subscriber exists
$SQL= "select email from tblnewsletter where email='".$email."'";
$result = mysql_query($SQL);
if(!$result) {die('Problem in SQL: '.$SQL);} //just checking if there was a problem with your query
if (mysql_num_rows($result)==1) { // he was subscribed already
echo 'You are subscribed.'; // Change the message if you want.
}
else { // does not exist ==> add to the table
$SQL2= "INSERT into tblnewsletter (email) VALUES ('".$email."')";
mysql_query($SQL2);
echo 'Thank you for subscribing'; // Change the message if you want.
}
?>
and here is my Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#nlsubmit').on('click', function() {
signup();
return false;
});
});
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function signup()
{
var emailentered = $("#email").val();
var email = trim(emailentered);
//EMAIL VALIDATION
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
var apos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
lastpos = email.length - 1;
var badEmail = (apos < 1 || dotpos - apos < 2 || lastpos - dotpos < 2);
if (email == "" || !goodEmail || badEmail)
{
//Email address fails
$('myResponse').style.display = 'inline';
$('myResponse').style.color = 'red';
alert('Please enter a valid email');
$('email').focus();
return false;
}
else
{
email = encodeURIComponent(email);
//Email address succeeds
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
}
}
function showResponse(req) {
$("loading").hide();
$("myResponse").innerHTML = req.responseText;
$("myResponse").style.display = "inline";
$("myResponse").style.color = "blue";
$("submit").show();
$("email").invoke('clear');
}
function showException(req) {
$("myResponse").innerHTML = req.responseText;
alert("An error occured while talking to the server. Please try again.");
$("loading", "myResponse").invoke('hide');
$("submit").show();
$("email").invoke('clear');
}
</script>
The form that is calling all this is as follows:
<form method="post" name="subform" id="subform" action="">
<input type="text" id="email" name="email" value="">
<input type="submit" id="nlsubmit" name="submit" value="Sign up">
<div id="myResponse" style="display:none;"></div>
<div id="loading" style="display:none;"><img src="/images/wait.gif" alt=""></div>
</form>
Like I said the newsletter table is updated great, though I'm needing the user to be notified on the same page if they are already present, if the email is invalid etc.
In your function:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
'result' refers to whatever was echoed on signup.php, so if result=="You are subscribed." that means that the email address already exists in the database, otherwise if result=="Thank you for subscribing" the email address is new to the database and the new user subscribed. So the function should look something like this:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
if(result=="You are subscribed.")
{
// notify user that email address already exists
}
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
Related
I have a form that gets data from the database using a server-side code when the user inserts the "user_id" field.
I have many fields on my form, the main field is the User ID field, when the user inserts his user ID all the other fields will get the user data from the database. I managed to do all of that but I cannot do one thing which is to auto-populate the fields when the "User_id" field is filled by a link parameter. Please follow that link: https://aaa-wa.com/form-new/?user_id=2 and you will see that the user ID field on my form is filled by the link parameter 2, but the data doesn't get auto-populated until you remove the number 2 and type it in on by your keyboard.
I need when the user follows the link I send to him like: aaa-wa.com/form-new/?user_id=2 I need all of his data to be filled automatically without the need to type in his user id by the keyboard
So the JavaScript should get the user ID from the query parameters, and use that in the AJAX call.
My HTML Code
<form name='form1'>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>User Id</label>
<input type='text' name="user_id"
id='id' class='form-control'
placeholder='Enter user id'
onkeyup="GetDetail(this.value)" value="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name"
id="first_name" class="form-control"
placeholder='First Name'
value="" required >
</div>
</div>
</div>
Javascript code
<script>
// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
if (str.length == 0) {
document.getElementById("first_name").value = "";
document.getElementById("last_name").value = "";
document.getElementById("phone_number").value = "";
return;
}
else {
// Creates a new XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
// Defines a function to be called when
// the readyState property changes
if (this.readyState == 4 &&
this.status == 200) {
// Typical action to be performed
// when the document is ready
var myObj = JSON.parse(this.responseText);
// Returns the response data as a
// string and store this array in
// a variable assign the value
// received to first name input field
document.getElementById
("first_name").value = myObj[0];
// Assign the value received to
// last name input field
document.getElementById(
"last_name").value = myObj[1];
// Assign the value received to
// last name input field
document.getElementById(
"phone_number").value = myObj[2];
}
};
// xhttp.open("GET", "filename", true);
xmlhttp.open("GET", "/wp-includes/gfg.php?user_id=" + str, true);
// Sends the request to the server
xmlhttp.send();
}
}
</script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#saveusers").on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var phone_number= $("#phone_number").val();
$.ajax({
method: "POST",
url: "/wp-includes/test1/saverecords_ajax.php",
data: { "first_name": first_name, "last_name": last_name, "email": email, "phone_number": phone_number},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
var cls = '';
if(result == 1) {
str = 'User record saved successfully.';
cls = 'success';
}else if( result == 2) {
str = 'Some of the fields are required.';
cls = 'error';
}else if( result == 3) {
str = 'Enter a valid email.';
cls = 'error';
}else if( result == 4) {
str = 'Enter a valid phone number.';
cls = 'error';
}else{
str = 'User data could not be saved. Please try again';
cls = 'error';
}
$("#message").show(3000).html(str).addClass('success').hide(5000);
});
});
});
</script><script>
function acceptParam() {
var hashParams = window.location.href.substr(1).split('?'); // substr(1) to remove the `#`
hashParams = hashParams[1].split('&');
var p = hashParams[0].split('=');
document.getElementById('id').value = p[1];
}
</script>
Call getDetail() in acceptParam(). And call acceptParam() when the page loads.
function acceptParam() {
var hashParams = window.location.href.substr(1).split('?'); // substr(1) to remove the `#`
hashParams = hashParams[1].split('&');
var p = hashParams[0].split('=');
document.getElementById('id').value = p[1];
getDetail(p[1]);
}
document.addEventListener("DOMContentLoaded", acceptParam);
I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}
when i click on submit button it will show me the message from the javascript file but it will not go to the php file that i have generated..
here is my html code
<form method="post" id="contactForm" action="email_send.php">
<div class="clearfix">
<div class="grid_6 alpha fll">
<input type="text" name="senderName" id="senderName" placeholder="Name *" class="requiredField" />
</div>
<div class="grid_6 omega flr">
<input type="text" name="senderEmail" id="senderEmail" placeholder="Email Address *" class="requiredField email" />
</div>
</div>
<div>
<textarea name="message" id="message" placeholder="Message *" class="requiredField"></textarea>
</div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
<span> </span>
</form><!-- end form -->
my js file
if ($("#contactForm")[0]) {
$('#contactForm').submit(function () {
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
my php file which i have written on action is
<?php
if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) )
{
$senderName = $_POST['senderName'];
$senderEmail = $_POST['senderEmail'];
$message = $_POST['message'];
if(!empty($senderName) && !empty($senderEmail) && !empty($message))
{
if(strlen($senderName)>25 || strlen($senderEmail)>25 || strlen($message)>50 )
{
echo 'Maximum length reached for each field';
}
else
{
$to = 'info#courtpiece.com';
$subject = 'Court Piece Rung';
$body = "Name:".$senderName."\n"."Message: ".$message;
$header = 'From'.$senderEmail;
if(#mail($to,$subject,$body,$header))
{
echo 'Thanks for Contacting Us.We\'ll in touch soon. ';
}
else
{
echo 'Sorry an error occured ';
}
}
}
else
{
echo 'All fields are required. ';
}
}
?>
Sometimes this can create a problem..
You are using: if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) ){
instead of:
if(isset($_POST['sendMessage'])){
if(!empty($_POST['senderName']) && !empty($_POST['senderEmail'])){
CODE HERE
}
}
If not, then probably you miss-confiugred your email sending service.
try a test on the email sending.
mail()
You will need to supress the default behaviour of your form so it doesnt also send a request to your server. You do this by calling the prevendDefault function of your event parameter .submit(function(e)....
if ($("#contactForm")[0]) {
$('#contactForm').submit(function (e) {
e.preventDefault(); //to suppress the behaviour of your Form -> you will send data manually with $.post
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post("email_send.php", formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
I have to say that there is room for improvement in the way you have built up this validation.
Try running the form again with the additions I made.
Report back!
I have a registration form that onsubmit runs a validation javascript function to check that
a:all the boxes have a value in them.
b:the password values match.
c: the email address is valid.
The email validation script makes an ajax call to check to see if the email address has been registered before.
It runs great in all browsers except Safari. In Safari it just hangs the page.
Heres the relevant parts of the code:
html form
<form name="login" action="<?php echo htmlspecialchars($pre_link.'register3.php'); ?>" method="post" onsubmit="return validateReg();">
<div id="register_label">Email Address:<span id="req">*</span></div>
<input class="register_input" id="myregusername" name="myusername" size="14"/><br><br>
<div id="register_label">Password:<span id="req">*</span></div>
<input class="register_input" id="mypassword" name="mypassword" size="14" type="password"/><br><br>
<div id="register_label">Confirm Password:<span id="req">*</span></div>
<input class="register_input" id="mypassword1" name="mypassword1" size="14" type="password"/><br><br>
<br /><br />
<input type="submit" id="loginBtn" name="submit" value="Next" />
</form>
the js validation code
function validateReg(){
var origBorder = "1px solid #CCCCCC";
var errorBorder = "1px solid red";
var myregusername = document.getElementById("myregusername");
var mypassword = document.getElementById("mypassword");
var mypassword1 = document.getElementById("mypassword1");
var errorstr = "";
var error = false;
myregusername.style.border = origBorder;
mypassword.style.border = origBorder;
mypassword1.style.border = origBorder;
if(myregusername.value.length == 0) {
errorstr = errorstr + "\n" + "Please enter your email address";
error = true;
myregusername.style.border = errorBorder;
}
if(mypassword.value.length<=5) {
errorstr = errorstr + "\n" + "Please enter your password that is at least 6 characters long";
error = true;
mypassword.style.border = errorBorder;
}
if(mypassword1.value!=mypassword.value) {
errorstr = errorstr + "\n" + "Your passwords do not match";
error = true;
mypassword.style.border = errorBorder;
mypassword1.style.border = errorBorder;
}
if(error) {
alert(errorstr);
return false;
} else {
if (checkMail()){
return true;
} else {
return false;
}
}
}
ajax code
function checkMail(){
var myusername = document.getElementById("myregusername") ;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(myusername.value)) {
function checkMail3(){
var myusername = document.getElementById("myregusername").value ;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(myusername)){
$.ajax({
url: "checkregemail.php",
type: "post",
headers: { "cache-control": "no-cache" },
data:{ username : myusername },
success: function(data) {
if(data=='1'){
alert("sorry this email address has already been registered\nClick login to sign in with his email address");
document.getElementById("myregusername").focus();
return false;
}else{
alert("good email address");
return true;
}
},
error:function(){
alert("failure");
}
});
} else {
var errorBorder = "1px solid red";
var error = false;
alert('Please enter a VALID email address');
myusername.style.border = errorBorder;
return false;
}
}
} else {
var errorBorder = "1px solid red";
var error = false;
alert('Please enter a VALID email address');
myusername.style.border = errorBorder;
return false;
}
}
If I remove the ajax call, then it runs fine in Safari.
I have read about Safari caching $post's but I don't have enough knowledge to be able to incorporate what I have found into my code and get it working. I have added the 'headers: { "cache-control": "no-cache" }, ' but that still doesnt fix the issue.
if the email is registered then it throws the error message but if the email is not found in the db, it throws the 'emailk good' alert but doesnt return the true to the original statement so the form does not get submitted
Any help would be greatly appreciated.
I am trying to do login with the help of Jquery ajax, but at the time of making ajax call using method jQuery.ajax(....) with servlet (Java) this method was unable to call. I am using ajax lib from link http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js.
Every time I am getting the below URL in address bar of browser.
Project/?email=abc88%40gmail.com&password=1234&sendbtn=Send+Message
Below is the Jquery Ajax Code.
$(document).ready(function() {
//global vars
var username=jQuery("#email");
var password=jQuery("#password");
function checkLoginForm() {
if(username.attr("value") && password.attr("value")) {
return true;
} else {
return false;
}
}
jQuery(".txtbar, .txtbox").live("focus", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
var pxlchange = '-45px';
rowbox.addClass('colors');
thelabel.animate({left: pxlchange}, 350, 'linear', function() {});
// The animation is completed
infobox.animate({opacity: 1.0}, 350, 'linear', function() {
// The animation is completed
});
}
jQuery(this).live("keyup", function() {
var theval = jQuery(this).val();
var limitval = 3;
var replacehtml = "";
var emailinfohtml = "Enter a valid e-mail address.";
var subjectinfohtml = "Enter Password.";
if(currid == "email") {
replacehtml = emailinfohtml;
} else if(currid == "password") {
replacehtml = subjectinfohtml;
limitval = 2;
}
// checking against e-mail regex
if(currid == "email") {
if(checkValidEmailAddress(theval)) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(!checkValidEmailAddress(theval)) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
} else {
// we use this logic to check for name+message fields
if(theval.length >= limitval) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(theval.length < limitval) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
}
// now we check if we can display the send button
// much easier to just look for 'good class on the req fields
});
});
jQuery(".txtbar, .txtbox").live("blur", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
rowbox.removeClass('colors');
infobox.animate({opacity: 0}, 400, 'linear', function() {
// The animation is completed
});
});
jQuery("#sendbtn").click(function() {
if (checkLoginForm()) {
jQuery.ajax({
type : "GET",
url : "/DoLogin.htm",data:"userName="+ username.val()+ "&password="+ password.val(),
success : function(msg) {
alert("Ajax Return Success");
return false;
}
});
} else {
alert("Ajax Return Fail Code ");
return false;
}
});
function checkValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+") ([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
HTML code:
<div id="wrap">
<form id="contact-form" name="contact-form">
<div class="rowbox">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" class="txtbar req" tabindex="1">
<div class="infobox">
Enter a valid e-mail address
</div>
</div>
<div class="rowbox">
<label for="subject">Password</label>
<input type="password" id="password" name="password" class="txtbar" tabindex="1">
<div class="infobox">
Enter Password
</div>
</div>
<input type="submit" value="Send Message" id="sendbtn" name="sendbtn" class="submit-button">
</form>
</div>
If you make the data property an object, jQuery will handle parameterizing and URI-encoding it for you automatically. If you insist on it being a string, you need to do all of that yourself.
jQuery.ajax({
type: "GET",
url: "/DoLogin.htm",
data: { userName: username.val(), password: password.val() },
success: function() {
alert("Ajax Return Success");
}
});
On a security note, I wouldn't simply check that the #email and #password fields have value attributes and return true, nor would I transmit plain-text login info over the wire. Maybe you intended this as boilerplate code to get things working and you'll validate/encrypt them better later. :)