I have a form. That form having some field as like Name, Phone No., Email and submit button
I have an AWS hosted server. have a database also. So I want to know one thing when user will type his name, and phone no. then pass the data to my database without user pressing submit.
Please help me to implement it.
What you are looking for is AJAX. I recommend you to use a library such as JQuery, which will make it a lot easier for you.
What you are looking for is most likely an onBlur method on your inputs. If your are typing in a textfield then it is focused, then when you change textfield it is Blurred. So you'd want something like, .
EDIT
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<form action="" method="post" id="ajaxForm">
<input type="text" id="name" name="name" placeholder="name">
<input type="text" id="phone" name="phone" placeholder="phone">
<input type="email" id="email" name="email" placeholder="email" onfocus="validateAndSubmit()">
<input type="submit" value="Send form">
</form>
<p><label id="result"></label></p>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
<!--
var validateAndSubmit = function()
{
var nameValue = $("#name").val();
var phoneValue = $("#phone").val();
//Validate the data - Do your custom validation here
if (nameValue.length > 3 && phoneValue.length > 5){
//Validation complete
$.post(
"your_save_file.php",
{ name: nameValue, phone:phoneValue },
function(data) {
alert("Data saved");
}
);
document.getElementById("result").innerHTML = "Validation completed";
} else {
//Not validated, do nothing
document.getElementById("result").innerHTML = "Validation failed";
}
};
-->
</script>
</body>
</html>
This will do what you requested. However, I would not recommend you to do this. Because if a user accidently submitted the wrong data then the data will already have been sent. I would recommend you to have a submit button that will activate the function.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have coded the following form with PHP & MySQL as database. I want to prevent the form from submitting data, if email address already exists in database. I also want to disable the submit button, if email exists in database.
Index.php:
<?php
require_once './include/user.php';
$user_obj = new user();
if (isset($_POST['submit'])) {
$message = $user_obj->save_user($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Form With JS Validation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/country.js"></script>
<script type="text/javascript" src="js/jsval.js"></script>
</head>
<body>
<p>PHP Form With JS Validation</p>
<div id="id1">
<form id="myForm" name="myForm" action="index.php" method="POST" onsubmit="return validateStandard(this)">
<table>
<tr><td><input type="text" name="name" value="" placeholder="name" required="required" regexp="JSVAL_RX_ALPHA"></td></tr>
<tr><td><input type="email" name="email" value="" placeholder="email" required="required" required regexp="JSVAL_RX_EMAIL"></td></tr>
<tr><td><input type="password" name="user_password" value="" placeholder="password" required="required"></td></tr>
<tr><td><input type="tel" name="phone" value="" placeholder="phone no" required="required"></td></tr>
<tr>
<td>
<input type="radio" name="gender" value="male" checked>Male
<input type="radio" name="gender" value="female">Female
</td>
</tr>
<tr><td><textarea name="address" placeholder="address" required="required"></textarea></td></tr>
<tr><td><input type="text" name="city" value="" placeholder="city" required regexp="JSVAL_RX_ALPHA"></td></tr>
<tr><td>
<select name="country" required="required" exclude=" ">
<option value=" ">Please Select Country</option>
<script type="text/javascript">printCountryOptions();</script>
</select>
</td></tr>
<tr><td><input type="text" name="zipcode" value="" placeholder="zipcode" required="required" regexp="JSVAL_RX_ALPHA_NUMERIC"></td></tr>
<tr><td><input type="checkbox" name="agree" value="on" required="required"> I agreed with all the terms!</td></tr>
<tr><td><input type="submit" id="sbtn" name="submit" value="Register"></td></tr>
</table>
</form>
</div>
</body>
</html>
<script>
document.forms['myForm'].reset();
</script>
db: user.php
<?php
class user {
public function save_user($data) {
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "db_user_info";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
$user_password = md5($data['user_password']);
$sql = "INSERT INTO tbl_user (name, email, user_password, phone, gender, address, city, country, zipcode, agree) VALUES ('$data[name]','$data[email]','$user_password', '$data[phone]','$data[gender]','$data[address]','$data[city]','$data[country]','$data[zipcode]','$data[agree]')";
if (!mysqli_query($conn, $sql)) {
die('Sql Error:' . mysqli_error($conn));
} else {
header('Location:thanks.php');
}
mysqli_close($conn);
}
}
To achieve this you will need ajax, you have two options
on the username field you can have an onblur event, then call a function that will check the username in the database using the onblur event.
<input name="username" type="text" id="username" onBlur="checkAvailability()">
The onblur event occurs when an object loses focus. The onblur event
is most often used with form validation code (e.g. when the user
leaves a form field).
With this method as soon as the user finishes typing the email address and leaves the input field, the checkAvailability() function is fired up and send Asynchronous request to the server using ajax. the user will know if the username is taken even before they can submit.
Collect all form data and return results when the submit button is hit without refreshing the page, (ajax as well).
Lets start with option 2 because its kinda easy.
First you will need to use prepared statements, also use php builtin password_hash and password_verify() functions for better safer passwords
lets begin, we will have a form with username field(email) only just you can see whats's happening, then when we click the register button we start our ajax that will call the php script and return json data back to use.
index.php
<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function (){
$('#register').submit(function (event){
var formData = {
'username' : $('input[name=username]').val()
};
$.ajax({
type : 'POST',
data : formData,
url : 'register.php',
dataType :'json',
encode : true
})
.done(function(data){
console.log(data); //debugging puroposes
if(!data.success){
if(data.errors.username){
$('#user-availability-status').append(data.errors.username);
}
if(data.errors.exists){
$('#user-availability-status').append(data.errors.exists);
$('#submit').prop('disabled', true);
}
}else{
$('#submit').prop('disabled', false);
$('#success').append('<div class="alert alert-success">'+data.message+'</div>');
// alert('done');
}
})
.fail(function(data){
console.log(data); //server errrors debugging puporses only
});
event.preventDefault();
});
});
</script>
<div id="frmCheckUsername">
<div id="success" class="status-available"></div>
<form method="POST" action="register.php" id="register">
<label>Username:</label>
<input name="username" type="text" id="username"><span id="user-availability-status" class="status-not-available"></span><br><br>
<button type="submit" name="submit" id="submit"> Register </button>
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
</form>
Register.php
<?php
require_once("dbcontroller.php");
$data = array();
$errors = array();
if (empty($_POST['username'])) {
$errors['username'] = 'enter username';
} else {
$username = $_POST['username'];
//check if username exists
$statement = $con->prepare("SELECT email FROM users WHERE email = ? LIMIT 1");
$statement->bind_param('s', $username);
$statement->execute();
$statement->store_result();
if ($statement->num_rows == 1) {
$errors['exists'] = 'the email ' . $username . ' already registered please login';
}
}
if (!empty($errors)) {
//We have errors send them back
$data['success'] = false;
$data['errors'] = $errors;
} else {
//No errors insert
$stmt = $con->prepare("INSERT INTO users (username) VALUES(?)");
$stmt->bind_param("s", $username);
$stmt->execute();
$data['success'] = true;
$data['message'] = 'user registered';
$stmt->close();
$con->close();
}
echo json_encode($data);
?>
dbcontroller.php is my database connection class, so you can ignore that and have your own.
This will point you to the correct direction atleast
Option 1 using the onblur event
<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "register.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
$('#submit').prop('disabled', true);
},
error:function (){}
});
}
</script>
<div id="frmCheckUsername">
<label>Check Username:</label>
<input name="username" type="text" id="username" onBlur="checkAvailability()"><span id="user-availability-status" class="status-not-available"></span> <br><br>
<button type="submit" name="submit" id="submit"> Register </button>
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
On this one as soon as the user leaves the input box the checkAvailability(); is fired up
you just check before that email already exist in Db
you just make an ajax request when user type email
then make an ajax if response is true just disabled submit button
You must use ajax.
http://api.jquery.com/jquery.ajax/
Your submit button default is disabled. After if the visitor write the e-mail address, you send the ajax query with this address to your backend, and it will return the e-mail status. If the email not exists in your database, the js remove disabled property from the button.
It's so similar like this: check username exists using ajax
Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});
i write sample code to ajax post javaxcript varible to php in 2 page, test.php and validate.php.
test.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.min.js" ></script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit" onclick="post();">
</form>
<div id="result" ></div>
<script type="text/javascript">
function post()
{
var name=$('#name').val();
var age=$('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data)
{
if (data=="1")
{
$('#result').html('you are over 18 !');
}
if (data=="0")
{
$('#result').html('you are under 18 !');
}
});
}
</script>
</body>
</html>
validate.php
<?php
$name=$_POST['postname'];
$age=$_POST['postage'];
if ($age>=18)
{
echo "1";
}
else
{
echo "0";
}
?>
how can i write/change above code in same page ?? and validate.php insert in test.php ??
added after first answer :
"but i dont have/use any button or in my page.
and where can i insert validate.php code in test.php. please help by insert complete correct code."
Try adding a submit() method to your <form> rather than attaching the event to the submit button.
$(document).on('submit', 'form', function(){
post();
return false;
});
At the moment I think your form is submitted no matter what, you have to either return false on submit or preventDefaults()
A good idea is also to add an ID to your form in case you have more than one on your page and use the relevant selector in the .on event handler such as
$(document).on('submit', $('#form-id'), function(){ ... });
ajax is use for exchanging data with a server. If you want write code in same page so reload page and write validate.php code above of test.php like this
<?php
//validate.php code
?>
<form action=test.php type=POST>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit">
</form>
I'm pretty strong with PHP, but javascript is totally new to me.
I need to add various ajax functionality to my projects, for example for form validation etc.
I've done some searching, watched some tutorials, and come up with a basic working example as follows:
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax form test</title>
<style>
form input, form textarea {
display:block;
margin:1em;
}
form label {
display:inline;
}
form button {
padding:1em;
}
</style>
</head>
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js:
$('form.ajax').on('submit', function() {
console.log('trigger');
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#form_content').load('server.php', data);
}
});
return false;
});
and finally, server.php:
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='')
{
?>
<h4>Your data was submitted as follows</h4>
<br />name: <?=$_POST['name']?>
<br />email: <?=$_POST['email']?>
<br />message: <?=$_POST['message']?>
<?php
} else {
?>
<h3>please fill in all form data correctly:</h3>
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
<?php
}
This all works fine, in that if I enter all form data and click submit, the ajax magic happens and I get a confirmation of the data. Also if not all data is loaded, the form is re-presented on the page. The problem is that in such a case, continuing to fill out the form data and then submit it loads the server.php page instead of repeating the ajax call until the form data is valid..
I'm sure there's a better way to do this as it's my first attempt, but I haven't been able to find any solution by searching either here or on google, but that's probably mostly because I don't really know what to search for. how can I make the behaviour in the first instance repeatable until the form is submitted correctly ?
This happens because you are removing your form element during your load() call and overwrite it with a new version of the form. Therefore all attached event handlers will vanish along with it.
You will need to use a delegate on an element that does not change:
$('#form_content').on('submit', 'form.ajax', function() {...});
Explanation:
In the above example, you attach the event listener to the #form_content element. However, it only listens to events that bubble up from the form.ajax submit event. Now, if you replace the form with a new version, the existing handler is attached higher up in the chain (on an element that doesn't get replaced) and continues to listen to events from lower elements, no matter if they change or not... therefore it will continue to work.
Your primary problem is that you are validating the form on the PHP side, when you should really validate it on the client side - THEN, instead of returning an appropriate response and continuing processing on the client side, you are finishing processing on the PHP side. Steve's answer (above) applies to what you are seeing.
As to the approach you have taken, it might be better to not use a <form> construction at all, because with AJAX you often don't need to. In my opinion, <form> is an archaic structure, not often needed in the age of AJAX. Notice how you had to add return false following the AJAX block to abort the default form functionality -- to stop it from sending the user over to server.php? That should tell you something.
Here is another way to structure it:
HTML:
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="button" id="mybutt" value="send">
</div>
<div id="responseDiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
JAVASCRIPT/JQUERY:
$(document).ready(function() {
//Next line's construction only necessary if button is injected HTML
//$(document).on('click', '#mybutt', function() {
//Otherwise, use this one:
$('#mybutt').click(function() {
console.log('trigger');
var valid = "yes";
var that = $(this),
url = "server.php",
type = "POST",
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (value=="") valid = "no";
data[name] = value;
});
if (valid == "yes") {
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#responseDiv').html(response);
/* OPTIONALLY, depending on what you make the PHP side echo out, something like:
if (response == "allgood") {
window.location.href = "http://www.google.com";
}else{
//this is how you would handle server-side validation
alert('Please complete all fields');
}
*/
}
}); //END AJAX
}else{
alert('Please complete all fields');
}
}); //END button.click
}); //END document.ready
PHP Side: server.php
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='') {
$r = '';
$r .= "<h4>Your data was submitted as follows</h4>";
$r .= "<br />name: " . $_POST['name'];
$r .= "<br />name: " . $_POST['email'];
$r .= "<br />name: " . $_POST['message'];
} else {
$r = "Please complete all form fields";
}
echo $r;
I created login from that when clicking submit button sends variables to login_success.php page.but I want to make that when I click submit button login form will be close. I can close form using Jquery
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
});
});
</script>
But this time form does not sends request to .php file. I made it like addin script to .php file and then redirected to index.html site.It also good but I can see reflection.How can I combine them?
this is my form
<div class="loginform">
<form action="php/login.php" method="post" id="login">
<fieldset class="loginfield">
<div>
<label for="username">User Name</label> <input type="text" id="username" name="username">
</div>
<div>
<label for="password">Password</label> <input type="password" id="password" name="password">
</div>
</fieldset>
<button type="submit" id="submit-go" ></button>
</form>
</div>
Edit
I used function as NAVEED sad .I installed FireBug in firefox and I can see that my form validation works normal.It sends and request to login.php But I cant make any change on my form.It does not close or $arr values not shown on div tags.
You should use JSON/AJAX combination:
Downlod jQuery
If your form look like this:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<div id='errors'></div>
<div class='loginform' id='loginform'>
<form action="php/login.php" method="post" id="login">
Username:<input type="text" id="username" name="username">
Password:<input type="password" id="password" name="password">
<button type="submit" id="submit-go" value='Login'></button>
</form>
</div>
Your jQuery Code in ajax.js file to submit the form and then get data from 'php/login.php' in JSON and fill the required DIVs. If login is id of the form.
jQuery('#login').live('submit',function(event) {
$.ajax({
url: 'php/login.php',
type: 'POST',
dataType: 'json',
data: $('#login').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
your login.php file as described in form action attribute:
$username = $_POST['username'];
$password = $_POST['password'];
if( $username and $password found in database ) {
// It will replace only id='loginform' DIV content
// and login form will disappear
$arr = array ( "loginform" => "you are logged in" );
} else {
// It will replace only id='errors' DIV content
$arr = array ( "errors" => "You are not authenticated. Please try again" );
}
echo json_encode( $arr );
More Detail:
How to submit a form in ajax/json:
General jquery function for all forms
Try submit method
$("button").click(function(){
$("form.loginform").submit().hide();
});
PS You do know that applying onclick handler to all <button> elements on the page is bad idea, right?
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
return false;
});
});