How to get response from ajax after selecting the auto completing email - php

I have a code to check email id is available or not in the database using ajax on keypress. If email Id is available then submit button will enable or email id is not available in the database then submit button will show disabled.
I have no issue in above process below code is working for above process.
My issue is some time users are getting the popup to store the username and password in the browser when the user entered the username and password. I am talking about cookies or can say auto-filed data. For example: If you enter the email id two or three times in text field then next time you clicked on the field you will automatically get your email.
Same issue I am getting. I saved the username and password on my browser and now I am selecting my username and clicking the button which is not working because I am using ajax on keypress. I f I type the email then it is working If I select the email then not working. I need if any user selects the email id than also button should active.
Hope you understand my issue .would you help me in this issue?
On keypress Getting ajax response
Auto filling the email the no response from ajax
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="submitYesNo" type="submit" name="next" value="submit" disabled="disabled">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
/*checking email id is already exist or not*/
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
$("#email-validation-error").html(data);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
PHP
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}

This function will work when the user click or focus outside of that input field otherwise it wont work
$("input[name='email']").bind('change keyup', function(){
console.log(this.value);
});
Check this once it may help on your scenario

Bind blur event with keyup event.So that when your textbox loose focus at that time your ajax can be called again
$("input[name='email']").on('keyup blur',function() // Add blur event
{

Related

Hiding a form upon click of the submission button

<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/

Calling an external jQuery function from php File

I have been trying to use Messi.js to return a pop up box if the user has an input error in a form. I have a php file called add email:
<?php
/ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>" && $_POST['emailAdd'] !="")
{
// the form was submitted
//remove hacker HTML
$email=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email'";
$result=mysql_query($sql2);
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Please enter a valid email.", {title: "Input error", modal:true});';
print '</script>';
}
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Sorry, you have entered an existing email.", {title: "Duplicate Email", modal:true});';
print '</script>';
}
?>
I am not sure where to call the jQuery files and css. I have done so in my index.php page(where the addEmail function is called) but it is still not working.
html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Club Blaque - Sign up for the Revolution</title>
<link href="css/reset.css" rel="stylesheet" type="text/css">
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/messi.min.css" rel="stylesheet" type="text/css"/>
<link href="js/jquery-1.8.2.js" type="text/javascript"/>
<script src="js/messi.js" type="text/javascript"></script>
Thanks in advance
EDIT
My form section currently looks as follows
<form name="emailAddr" method="post" action="">
<p>BE INVITED TO THE REVOLUTION <input id="emailAddress" name="emailAdd" type="text" value="<<please enter email>>" onFocus="clearText(this)" onblur="addText(this)"/>
<button type="submit" name="submit" value="Submit"><img id="submitImage"src='image/submit.ico'/></button> </p>
</form>
You can do the field validation testing in jQuery/javascript before even POSTing the form. That way you can trap errors without refreshing the page.
Note how the Submit button is type="button", not type="submit". The submit function is done via jQuery.
See below stand-alone, fully working example.
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="myform" action="yourphpprocessor.php" method="POST">
Email Address:<br />
<input id="emailAdd" name="emailAdd" type="text" /><br />
Password:<br />
<input id="pwordAdd" name="pwordAdd" type="password" /><br />
<input type="button" id="mybutt" value="Submit It" />
</form>
</body>
</html>
Note that if you wish to store the javascript/jQuery in an external file the code would look something like this:
<script type="text/javascript" src='myjavascript.js'></script>
And the file myjavascript.js would look like this:
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
For querying the database during field validation, use AJAX. It allows you to send the email address off to a PHP file (let's call it your PHP processor file), do the database lookup, and return a response. The response is anything that you want to build: from a simple 1 or 0 response, to a fully formatted HTML response that you will post into a DIV. In your case, a simple 1 or 0 will be fine.
First thing you must decide is how you want to trigger the AJAX lookup. You could use Submit button, but in our example let's use the jQuery blur() selector as it is triggered the moment a user leaves a field.
$('#emailAdd').blur(function() {
//Test if this email already exists
var em = $('#emailAdd').val();
$.ajax({
type: "POST",
url: "myphpprocessor.php",
data: 'eml='+em+'&anothervar='+summatelse,
success: function(whatigot) {
alert(whatigot);
if (whatigot == 'itexists') {
alert('This email address already exists. Please choose another.');
$('#emailAdd').css({'background-color':'yellow','border-color':'red'});
$('#emailAdd').focus();
}
} //END success callback
}); //END ajax block
}); //END emailAdd.blur
An Important Note About AJAX: All processing of received info must happen in the success: function. So, for example, the error message must happen in there. Once you start working with AJAX (95% of which is in this example - it's not very difficult), this note must be your Bible. Remember it.
Your PHP processor file would look like this:
myphpprocessor.php
<?php
$email = $_POST['eml']; //Note that it is same as the var NAME posted in AJAX
$summat = $_POST['anothervar'];
if ($email != '' && $email != '<<please enter email>>') {
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM `ClientEmail` WHERE `ClientEmailAddress` = '$email'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num > 0) {
echo 'itexists';
}else{
//do nothing
}
}

How do you clear form field after submit/success?

I'm working with this exact same MailChimp PHP/AJAX subscribe processing form - clear text value after success? - but I am absolutely stumped on how to actually get the form field to cleat after success.
Apparently to what Felix recommended here - clear text value after success? - the code works only if the span element exists at document load, and you have to call the if-statement after completion if using Ajax.
Could someone please help me? How do you clear the form field after it has been successfully completed by a user?
Here is the code:
<?php
// store-address.php
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('my-api-key');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "my-list";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form code:
<form action="<?=$_SERVER['PHP_SELF']; ?>" id="signup" class="subscribe" method="get">
<fieldset>
<input type="text" id="email" name="email" placeholder="your email address" />
<input type="submit" name="submit" value="Send it" />
</fieldset>
</form>
<p id="response"><? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?></p>
<script type="text/javascript" src="/js/prototype.js"></script>
<script type="text/javascript" src="/js/mailing-list.js"></script>
The mailing-list javascript code:
// Load Events Listeners
Event.observe(window, 'load', init, false);
function init(){
Event.observe('signup','submit',storeAddress);
}
// AJAX call sending sign up info to store-address.php
function storeAddress(event) {
// Update user interface
$('response').innerHTML = 'Getting email address...';
// Prepare query string and send AJAX request
var pars = 'ajax=true&email=' + escape($F('email'));
var myAjax = new Ajax.Updater('response', 'inc/store-address.php', {method: 'get', parameters: pars});
Event.stop(event); // Stop form from submitting when JS is enabled
}
There are two solutions to this.
The less elegant one would be to create a JS function the resets every form field value manually.
The better way would be to store a hidden reset input in your form with an ID:
<input type="reset" id="blagh" style="display:none"/>
And simply 'click' it using jQuery:
$('#blagh').click();
The jquery form plugin has resetForm(). Just sayin'.

validate a form before submit the data

I'm trying to validate a form before posting the data. Basically the form asks for a code. After the user clicks the submit button, the javascript below checks if the code only contains numbers and has a length of 6 digit. If the code is valid, then an ajax call is made calling the page verifybkcd.php, which runs a query and checks if the input code has associated with an account. Somehow the form is always submitted no matter what code I put.It seemed the ajax call has never been made because none of the alerts inside the call had been triggered. (I'm sure the path of the file verifybkcd.php is correct). Any ideas?
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$("#recovform").submit(function(e){
alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
alert("alert on code exists");
e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
alert("alert on valid");
$("#err-box").text("");
}
});
});
}
else{
$("#err-box").text("Please enter a valid book code above");
e.preventDefault();
}
});
The following is taken from the php file which has the form
<div id="container">
<?php
if($_SERVER['QUERY_STRING']==''){
?>
<div class="title"><h1>Forgot your password?</h1></div>
<div class="description"><p>To reset your password, enter the book code that you used when you registered your account.</p></div>
<form id="recovform" name="recovform" method="post" action="recovery.php?verifyuser" >
<div id="bkbox">
<label for="bkcode">Book Code:</label>
<input id="bkcode" name="bkcode" type="text" />
<input id="bksubmit" name="submit" type="submit" value="Submit"/>
</div>
<div id="err-box"></div>
</form>
<?php
}
else if($_SERVER['QUERY_STRING']=='verifyuser'){
?>
<div class="title"><h1>verify user</h1></div>
<div class="description"><p>emails below</p></div>
<?php
}
else{
echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../err/404.php'>";
}
?>
</div>
BTW, I'm sure there's nothing wrong with verifybkcd.php file. I've tested it with different codes. It will only return a string when there're no accounts associated with the input code.
Problem solved. I replaced the name of the submit button with something else. Then it worked like magic. Also I've made a little change on the javascript as follows. It seems jquery won't submit the form if you name the submit button "submit". BTW I aslo changed the type of the submit button to "button" instead of "submit"
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
if(data !=''){
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
$("#err-box").text("");
$("#recovform").trigger("submit");
}
});
}
else{
$("#err-box").text("Please enter a valid book code above");
}
});
});
First place if you dont want to submit the form then you should return false in the submit button click handler. Check if this below condition satisfied or not.
$(document).ready(function(){
//This is to prevent the form to be submitted
$("#recovform").submit(function(e){
e.preventDefault();
});
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
//$("#recovform").submit(function(e){
//alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
//alert("alert on code exists");
//e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
//alert("alert on valid");
$("#err-box").text("");
$("#recovform").unbind('submit').submit();
}
});
//});
}
else{
$("#err-box").text("Please enter a valid book code above");
return false;
}
});
in your example, you are missing:
})
at the end to close your $(document).ready in the javascript.

how to create a log in window where my username and password is from a server?

i have this html and javascript program code for log in window. my html is:
<body>
<div >
<h1>Sign in to me</h1>
<form id="login" method="get" action='exercises/exercise6/DynamicMenu_createTab_json.html'>
<div>UserName<input type="text" id="username" value="admin"/></div>
<div>Password<input type="password" id="password"/></div>
<div><input type="button" id="btnLogin" value="Login"/></div>
</div>
</body>
my javascript is:
$(document).ready(function(){
$('#username').focus();
$('form#login :submit').addClass('inputSubmitBtn').click(function(){
if($('#username').val() != "jay" || $('#password').val() != "son"){
alert('username/password incorrect');
$("#username").focus();
return false;
};
});
});
there's no problem in this program. what i wanted to do is i want to log in using my username and password from a server. and if it is succesful, it will open my other exercise html on the same window. here's my current code:
$('form#login :submit').addClass('inputSubmitBtn').click(function(){
var params = {
"UserName":$("#username").val(),
"Password":$("#password").val()
};
$.getJSON(
'process.php', 'path=Login&json=' + JSON.stringify(params),
function(data) {
if ('error' in data)
{
alert('password and username incorrect');
return false;
}
else
{
$("#sessionID").html(data["result"]["SessionID"]);
}
});
});
this code doesn't function right. please, can someone help me on this...
EDIT: here's my php code:
<?php
echo(file_get_contents("http://localhost/" . $_GET["path"] . "?json=" . $_GET["json"]));
?>
First the :submit selector returns nothing, you don't have a submit button ("type=submit"), so the click listener will never be called. See :submit selector.
Second you don't stop the submit event of the form, so the "action" attribute is used and the form is submitted, canceling the click listener function. (url 'exercises/exercise6/DynamicMenu_createTab_json.html' will be loaded)
You need to stop the event, else the form "action" will fire when the form is submitted.
$('#login :submit').click(function(event){ event.preventDefault(); ... });
And last, a click event listener function on the submit button will not fire 100% of the time.
For exemple when user press "enter" key while in a field of the form, no click on the button and the form is submitted.
Bind a submit event listener on the form instead.
$('#login').submit(function(event){ ... });

Categories