Currently the below script works brillantly checking the database using ajax to see if the email address has been used before. My question is how do I stop it checking the database until it is a fully defined EMAIL address?
Form field
<label for="email">Email: * </label><br/>
<input id="username" name="username" type="email" value="" onblur="return check_username();" />
AJAX script
<script type="text/javascript">
$(document).ready(function() {
$('#Loading').hide();
});
function check_username(){
var username = $("#username").val();
if(username.length > 2){
$.post("../script/check_username_availablity.php", {
username: $('#username').val(),
}, function(response){
$('#Info').fadeOut();
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(1000);
}
</script>
Instead of if(username.length > 2){... use something like:
if (/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(username.val())) {...
see http://jsfiddle.net/cmontgomery/gEL7n/
very similar to what ialencar posted:
isValidateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
check_username = function() {
var username = $("#username").val();
if(isValidateEmail(username)) {
$("#username-error").html("");
console.log("ajax request...");
} else {
$("#username-error").html("invalid email address");
}
}
Related
I'm looking to retrieve a user's avatar using their user name, retrieve it in an input field. However what I did does not work and I am not familiar with Ajax. Could someone help me and explain the procedure to me?
<input type="text" name="username" class="input" placeholder="Your username">
<img id="#result" src=""></img>
Here is my ajax
$(document).keyup(function (event) {
$.ajax({
url: "App/Actions/PlayerGetFigure.php",
type: "post",
data: {
login: function () {
return $(':input[name="username"]').val();
},
},
success: function (data) {
$('#result').html(data);
}
});
});
And here is my PHP
require '../../vendor/autoload.php';
use App\Models\UsersManager as Users;
$Users = new Users();
$username = $_POST['username'];
if (isset($username)) {
$user = $Users->getByUsername($username);
if ($user) {
echo $user['avatar'];
} else {
return false;
}
}
I would personally take this approach, it looks a bit cleaner for me (assuming that $user['avatar'] returns the path to the image)
HTML
<input type="text" id="username" class="input" placeholder="Your username" />
<div id="result"></div>
AJAX
$(document).keyup(function (event) {
let username = $('#username').val();
$.ajax({
url: "App/Actions/PlayerGetFigure.php",
type: "post",
data: { login:username },
success: function (data) {
$('#result').html(data);
}
});
});
PHP
require '../../vendor/autoload.php';
use App\Models\UsersManager as Users;
$Users = new Users();
$username = $_POST['username'];
if (isset($username)) {
$user = $Users->getByUsername($username);
if ($user) {
$avatar = $user['avatar'];
echo "<img src='$avatar'></img>";
} else {
return false;
}
}
If this is your HTML:
<input type="text" name="username" class="input" placeholder="Your username">
<img id="result" src=""></img>
I would advise the following jQuery.
$(function(){
function getAvatar(username){
var url = "";
$.post("App/Actions/PlayerGetFigure.php", { login: username }, function(data){
url = data;
});
return url;
}
$("input[type='username']").change(function(){
$("#result").attr("src", getAvatar($(this).val()));
});
});
This assumes that the PHP Script will return a (Relative or Absolute) URL Path to the Image.
So generally I have a form whose action is a link that verifies the user's username and password (can't post the link does not belong to me) and if it's correct it gives me an "ok" or else a "no"
How can I make it in a way that if yes it directs me to my index page and if no gives an error or reloads the page or something. Is their a way to do that
the general html appearance is:
<form method="post" action="https://***************/login">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in">
</form>
so if I were to change it into the way I want it then the action should change into something like verify.php which would have the appearance of
<?php
# how do I use an if for a link using the info that was input
if($_POST["https://***************/login"]){
#load index.html
?>
<script type="text/javascript">
window.location.href = 'index.html';
</script>
<?php
else{
#load the page again
?>
<script type="text/javascript">
window.location.href = 'login.php';
</script>
<?php
}
?>
I'm a bit new to php.
So please help
There is a header to redirect, you have to put it in your php script :
header('Location: yoururl.com');
To record error from your script, you can set it in $_SESSION variables :
session_start(); // at the beginning of your script
$_SESSION['error'] = 'Password incorrect, please try again';
And so, in your other page, you can use something like :
if($_SESSION['error']) {
echo $_SESSION['error']; // display error
$_SESSION['error'] = ''; // delete it
}
Being unable to edit the login verification file, I think your best option is to submit the form via ajax and handle its response with javascript, having your form like
<form method="post" action="" onsubmit="return false;">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in" onclick="btnAuthenticateUser();">
</form>
then, in plain javascript something like
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function btnAuthenticateUser() {
try {
var username = document.getElementById('username');
var pwd = document.getElementById('password');
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = 'https://***************/login?username=' + username.value + '&password=' + pwd.value;
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
if (xmlHttp.responseText == "ok") {
window.location = "index.html";
} else {
location.reload();
}
}
if (xmlHttp.readyState == 4) {
// LoadingPage
}
}
}
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
if (xmlHttp.readyState == 1) {
//LoadingPage
}
} catch (e) {
alert(e.Message);
}
}
</script>
or if you're using jQuery
function btnAuthenticateUser() {
$.ajax({
async: true,
type: 'POST',
url: 'https://***************/login',
data: { username: $('#username').val(), password: $('#password').val()}
})
.done(function (data) {
if (data == "ok") {
window.location = "index.html";
}else{
location.reload();
}
})
.fail(function (jqxhr, textStatus, error) {
GriterError(Global.FailTryAgain);
});
}
You can perform the action you need on your verification script and then throw in a redirect using the headers in PHP.
After the verification action you can choose which page to go to through an if/then statement
for example:
if ([the action you wanted succeeded]) {
header('Location: index.php');
}
else {
header('Location: login.php');
}
I have a specific request from a client that a newsletter signup be sent to a CSV file. I am a noob when it comes to anything backend, let alone frontend development.
I have a template that I am working from and can't make sense of the way it delivers the values.
The form code is quite simple
<form action="" method="post" class="signup" id="newsletter-form">
<p>
<input type="text" name="signup_name" id="signup_name" class="required" value="Your Name" />
</p>
<p>
<input type="text" name="signup_email" id="signup_email" class="required" value="Your E-mail" />
</p>
<input type="submit" value="SEND" class="signupSubmit" id="submitform" />
<div id="newsletter-msg-wrapper" style="position:relative; clear:both; width:100%;">
<div id="newsletter-loader"></div> <span id="newsletter-msg"> </span>
</div>
</form>
Then I have this .js file that seems to be handling the post
$(document).ready(function () {
var contactFormDefaults = new Array();
contactFormDefaults['name'] = 'Your Name';
contactFormDefaults['email'] = 'E-mail';
contactFormDefaults['subject'] = 'Subject';
contactFormDefaults['message'] = 'Message';
contactFormDefaults['msg'] = $('.contactForm span#msg').html();
$('.contactForm input[type="text"], .contactForm textarea').focus(function () {
$(this).addClass('inputHighlight').removeClass('errorOutline');
if ($(this).hasClass('required')) {
$('.contactForm span#msg').html('This is a required field.').removeClass('errorMsg successMsg');
} else {
$('.contactForm span#msg').html(contactFormDefaults['msg']).removeClass('errorMsg successMsg');
}
if ($(this).val() == contactFormDefaults[$(this).attr('id')]) {
$(this).val('');
}
});
$('.contactForm input[type="text"], .contactForm textarea').blur(function () {
$(this).removeClass('inputHighlight');
$('.contactForm span#msg').html(contactFormDefaults['msg']).removeClass('errorMsg successMsg');
if ($(this).val() == '') {
$(this).val(contactFormDefaults[$(this).attr('id')]);
}
});
$('.contactForm input[type="text"], .contactForm textarea').hover(function () {
$(this).addClass('inputHighlight');
}, function () {
$(this).not(':focus').removeClass('inputHighlight');
});
$('.contactForm').submit(function () {
$('.contactForm .submit').attr("disabled", "disabled");
$('#msg').html('<img src="images/loader-light.gif" />').removeClass('errorMsg successMsg');
var isError = false;
$('.contactForm input, .contactForm textarea').each(function () {
if ($(this).hasClass('required') && ($.trim($(this).val()) == contactFormDefaults[$(this).attr('id')] || $.trim($(this).val()) == '')) {
$(this).addClass('errorOutline');
$('#msg').html('There was an error sending your message. Please try again.').addClass('errorMsg');
isError = true;
}
if ($(this).attr('id') == 'email') {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test($(this).val()) == false) {
$(this).addClass('errorOutline');
if (!isError) {
$('#msg').html('Please enter a valid e-mail address and try again.').addClass('errorMsg');
}
isError = true;
}
}
});
if (isError) {
$('.contactForm .submit').removeAttr("disabled");
return false;
} else {
var name = $('#name').val(),
email = $('#email').val(),
subject = $('#subject').val(),
message = $('#message').val();
$.ajaxSetup({
cache: false
});
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message + '&ajax=1';
$.ajax({
type: "POST",
url: "../myform.php",
data: dataString,
success: function (msg) {
// Check to see if the mail was successfully sent
if (msg == 'Mail sent') {
// Update the progress bar
$('#msg').html('Message sent.').addClass('successMsg');
// Reset the subject field and message textbox
if (contactFormDefaults['subject']) {
$('#subject').val(contactFormDefaults['subject']);
} else {
$('#subject').val('');
}
if (contactFormDefaults['message']) {
$('#message').val(contactFormDefaults['message']);
} else {
$('#message').val('');
}
} else {
$('#msg').html('There was an error sending your email. Please try again.').addClass('errorMsg');
$('.contactForm .submit').attr("disabled", "");
}
// Activate the submit button
$('.contactForm .submit').removeAttr("disabled");
},
error: function (ob, errStr) {
$('#msg').html('There was an error sending your email. Please try again.').addClass('errorMsg');
//Activate the submit button
$('.contactForm .submit').removeAttr("disabled");
}
});
return false;
}
});
});
If possible I'd love to know how to make this all function and what I am not seeing here and how this all can be written into a CSV file.
A full view of the site and code can be viewed here:
www.cndnsd.com/ClientAccess/Newmarket/FinalSite/index.html
The form is at the bottom of the page.
in your myform.php , receive all the data (email, name etc) and start creating your CSV file. It is a simple operation and not that complicated.
For CSV file writing, please check out these posts on stack overflow:
write into csv file in php
Creating csv file with php
Also do some googling.
Hopefully this will help you.
Trying to do a simple web app with jquery mobile. I have put together a simple log in form with ajax results to be displayed. Problem is my ajax is not getting a result even when I alert out to see if the URL is valid. Is there something special I need to do using jquery mobile?
Any thoughts/answers much appreciated!
Here is the HTML code:
<div data-role="page" id="login" data-theme="a" data-add-back-btn="true">
<div data-role="header">
<h2>Log in</h2>
</div>
<div data-role="content" data-theme="a" data-add-back-btn="true">
<form action="mobilelogin.php" method="post">
Email: <input type="text" name="email" id="useremail">
Password: <input type="password" name="password" id="userpassword">
<input type="submit" value="Enter">
</form>
<div id="loginresult"></div>
</div>
<div data-role="footer"><h4>Chris Sherwood Design 2012</h4></div>
</div>
Js file:
$(document).ready(function() {
$('form').submit(function() {
var emailchecker = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $("#useremail").val();
var userpassword = $("#userpassword").val();
var checklength = userpassword.length;
if(email == ""){
alert('Please fill in email field');
return false;
}else if(userpassword == ""){
alert('Please fill in password field');
return false;
}else if((!emailchecker.test(email))){
alert('Please use a valid email');
return false;
}else if(checklength < 6 || checklength > 6){
alert('Password must be six characters');
return false;
}else{
var datastring = $(this).serialize();
alert(datastring);
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
}
});
PHP
<?php
echo 'nothing special here...';
?>
From your code:
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
You are returning false before the ajax request.
EDIT (assumed it was a simple mistake, have added more explanation)
You will need to either move that return false; to below the ajax() call, or use the event object like so:
$('form').submit(function(e) {
e.preventDefault();
The problem with just using return false; is that if there is an error in something before it it will not stop the default action. So if your ajax request errors it will miss the return false; and start loading the action page.
I am trying to add Jquery login submission with PHP. I was able to bind to LDAP without JQuery and login - OK. But as soon as I add JQuery code it sends the error:
ldap_bind() [function.ldap-bind]: Unable to bind to server: Invalid credentials.
I did a lot of searching and still missing something, but not quite sure what... :(
Here is what I have so far:
<script type"text/javascript">
var username = $("input#username").val();
var password = $("input#password").val();
var dataString = 'username='+ username + '&password=' + password;
$(document).ready(function(){
$("form#memberlogin").submit(function() {
$.ajax({
type: "POST",
url: "verification.php",
data: dataString,
success: function(data){
if(data.success) {
$('form#memberlogin').hide()
$('div.success').fadeIn();
}
else {
alert(data);
}
}
});
return false;
});
});
</script>
This is my verification.php :
// LDAP variables
$ldap['user'] = $_POST["username"];
$ldap['pass'] = $_POST["password"];
$ldap['host'] = 'my.server.com'; // host or server name
$ldap['port'] = 389; // LDAP port on the server
$ldap['dn'] = 'uid='.$ldap['user'].',cn=users,dc=my,dc=server,dc=com'; // LDAP search
$ldap['base'] = ' ';
// connect to LDAP
$ldap['conn'] = ldap_connect( $ldap['host'], $ldap['port'] );
ldap_set_option($ldap['conn'], LDAP_OPT_PROTOCOL_VERSION, 3);
// match user and password
$ldap['bind'] = ldap_bind( $ldap['conn'], $ldap['dn'], $ldap['pass'] );
if ($ldap['bind']){
session_cache_limiter('nocache,private');
$_SESSION['username']=$_POST["username"];
$_SESSION['password']=$_POST["password"];
$_SESSION['user_date']= date("Y-n-j H:i:s");
$page=$_SERVER['PHP_SELF'];
echo "success!";
}
else
{
echo "login failed...";
exit();
}
?>
and here is the form:
<form id="memberlogin" method="POST">
<fieldset>
<legend>Please login:</legent>
<label for="username">Username:</label>
<input id="username" class="text_inputs" type="text" name="username" size="20" class="imputbox">
<label for="username">Password:</label>
<input name="password" class="text_input" type="password" name="password" size="20" class="imputbox">
<input type="submit" name="submit" value="access" />
</fieldset>
</form>
Your problem is in HTML: your password field has 2 name attributes but no id, that's why password you send is always empty.
I would recommend to rewrite your code to avoid repitition.
$(document).ready(function() {
$("form#memberlogin").submit(function(e) {
// instead of creating data string by hand just .serialize your form
dataString = $(this).serialize();
$.post("verification.php", dataString, function(data) {
$('form#memberlogin').hide();
$('div.success').fadeIn();
});
e.preventDefault(); // this is better than "return false"
});
});