Auto Fill second textbox with first textbox input - php

auto fill second textbox with the input of first textbox. Like if I choose Jane as first name I want the second textbox to retrieve the last name from database and auto fill it with Doe. I am getting no auto input on second textbox not sure what I am doing wrong.
Here is the test.php code
<?php
?>
<script src="jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$("#firstName").change(function(){
var firstName=$(this).val();
if(firstName != ''){
$.ajax({
type:"post",
url:"insert_process.php",
data:"firstName="+firstName,
datatype:"json",
success:function(data){ $("#lastname").val(data);
$('#ename').css( "background-color","#B3CBD6" )
$('#ename').animate({backgroundColor: "#fff",});
}
});
}
else{
$("#lastname").val("");
}
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Systems Request </title>
</head>
<body>
<div align="center">
<form action = "insert.php" method ="post" class="form" style="width: 285px; height: 192px">
<br><br>First Name<br>
<input type="text" id="firstName" name="firstName">
<br> Last Name<br>
<input type="text" id="lastname" name="lastname" ><br><br>
<input type="submit" value= "Submit Name "><br>
</form>
</div>
</body>
</html>
and then here is insert_proccess.php code
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "root";
$db_name= "people";
$pass= "systems399";
$con = mysql_connect($host, $user, $pass);
$db_conx=mysql_select_db("people", $con);
$fname= $_POST["firstName"];
$sql="SELECT * FROM names WHERE firstName='$fname' ";
$query= mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query2 MYSQLI_ASSOC);
$rc = $row["lastname"];
echo json_encode ($rc);
?>

Is the request actually being sent (you can checking the networking tab)? Can you alert the returned data? Basically to be more helpful I would need more information on where exactly the process is failing, at a quick glance, try setting up your data structure more like this:
data: { "firstName": firstName }

Related

how to retrieve data from database and display in textbox using php ajax and jquery?

can anyone tell me how to retrieve data from database and display it in text box in html by using php ajax and jquery? it will just only display if the button is click. Thanks for helping!
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>registion</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$('#btn').click(function () {
$.post(
'checkUserName.php',{
username:$('#username').val()
},function(data,textStatus){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<h1>registion</h1>
<form action="" method="post">
userNameļ¼š<input type="text" name="username" id="username">
<input type="button" value="Verify userName" id="btn">
<br>
<span id="result"></span>
</form>
</body>
</html>
checkUserName.php
<?php
$uname = $_POST['username'];
$conn = mysqli_connect('localhost','root','root','db_user');
$query = "SELECT * from tb_user where name = '$uname' ";
$result = mysqli_query($conn,$query);
$nums = mysqli_num_rows($result);
//echo $query;
//echo $nums;
if($nums > 0){
echo "Username already exist";
}else{
echo "Username OK";
}
mysqli_close($conn);
Next time please post together what have you done so far. From there only the community will be able to help you.
HTML Code :
<input type="text" id="input-box">
<button type="button" id="btn_get">Click</button>
Ajax Code :
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box').val(data);
}
});
});
PHP Code :
//get data from db here
$data = 'foo';
echo $data;

Retrieve and print data to textboxes from mysql DB using ajax

I have the following text fields:
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname()">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="name" tabindex="3"/>
<input type="text" name="state" id="name" tabindex="4"/>
and database table is:
empid name city state
EMP471 BBB bbbbb cccccc
EMP444 AAA xxxx yyyyyy
I'm new to php. I found some code on internet to retrieve data. but its not working.
Ajax code is:
function getname() {
var id=$("#id").val();
$.ajax({
type:"post",
dataType:"text",
data:"id="+id,
url:"getinsdata.php",
success:function(response)
{
$("#name").val(response.name);
$("#city").val(response.city);
$("#state").val(response.state);
}
});
}
and php code is
<?php
include 'connection.php';
$id=$_POST['id'];
$id=$_POST['id'];
$query=mysql_query("select name,city,state from ins_master where id=$id");
$result=mysql_fetch_row($query);
echo $result[0];
exit;
?>
when we select the empid then the respective name, city, state should be shown in textboxes when onblur event fires in PHP using AJAX.
What are you trying to achieve? Send the datas and get the response according to a query? Get some datas?
I'd go
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</head>
<body>
<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password" id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<div id="answer"></div>
</body>
<script>
$("#sub").click(function(event){
event.preventDefault();
query = $.post({
url : 'check_ajax.php',
data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
});
query.done(function(response){
$('#answer').html(response);
});
});
</script>
This is check_ajax.php :
<?php
var_dump($_POST);
?>
in the second file but that's where you're supposed to do your query and insert/select
As people said we don't write code but give clues and since it's basics/fundamentals I can't help more cause you have to understand. Copy paste ain't a great idea
Try this html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
function getname(val) {
$.ajax({
url: 'getinsdata.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var name = data[0]['name'];
var city = data[0]['city'];
var state = data[0]['state'];
document.getElementById('name').value = name;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
}
}
});
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname(this.value);">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="city" tabindex="3"/>
<input type="text" name="state" id="state" tabindex="4"/>
</form>
</body>
</html>
and getinsdata.php is
<?php
include('connection.php');
$id = $_POST['state_id'];
$sql = "SELECT * FROM ins_master WHERE id='$id'";
$result = mysqli_query($conn,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id = $row['id'];
$name = $row['name'];
$city = $row['city'];
$state = $row['state'];
$users_arr[] = array("id" => $id, "name" => $name, "city" => $city, "state" => $state);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
?>
And your connection.php
<?php
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect("localhost",$username,$password,$dbname);
if(!$conn){
die("Error in Connecation");
}
?>
put $dbname= your database name

How to use ajax in Google Chrome extention

i want to insert data to server using ajax in my chrome extension so my users can sign up to use my extension.
i am desperately finding solution not not find the example
when i code ajax on popup.html i got this error
"Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-lXzxt12nj+7ATE1j5ucGnYo1VkLZpNS/cGA9SL9nCv0='), or a nonce ('nonce-...') is required to enable inline execution."
popup.html Code
<!DOCTYPE html>
<html>
<head>
<style>
body {
width:300px;
font-size:12px;
}
</style>
</head>
<body>
<form action="" method="POST">
<input type="text" id="name" name="uname">
<input type="text" id="pass" name="upass">
<input type="submit" id="submit" name="submit" id="btn">
</form>
</body>
</html>
<script type="text/javascript" src="check.js"></script>
<script type="text/javascript">
$("#btn").click(function(){
var btn =$('#btn').val();
var name= $('#name').val();
var pas = $('#pass').val();
$.ajax({
data :{btn: btn, name : name, pas: pas},
method="POST",
url:"http://localhost/status/index.php",
success : function(data){
lb.val(data);
}
});
});
}
</script>
index.php code which is on server
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['byn'])){
$localIP = getHostByName(getHostName());
$name = $_POST['name'];
$pass = $_POST['pass'];
$insert = mysqli_query($conn,"INSERT INTO usercheck VALUES('','$name','$pass','1111,'$localIP')");
}
?>

How to stop form submission if email address is already available in MySQL db ? [closed]

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

Not inserting data to MySql database

$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact;
if(name==''||email==''||password==''||contact=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="css/refreshform.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<h2>Submit Form Using AJAX and jQuery</h2> <!-- Required div Starts Here -->
<div id="form">
<h3>Fill Your Information !</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<label>Contact No :</label>
<input id="contact" type="text">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
This is what I have in ajaxsubmit.php
$host = "myhost";
$user = "myusername";
$password = "******";
$database = "thisismydb";
$connection = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$contact2=$_POST['contact1'];
//Insert query
mysqli_query($connection,"SELECT * FROM databasetable");
mysqli_query($connection,"INSERT INTO databasetable (name, email, password, contact)
VALUES ($name2', '$email2', '$password2','$contact2')");
mysqli_close($connection);
?>
However whenever i click submit it only gives me an alert that shows the code from the ajaxsubmit.php and i dont know what I'm doing wrong D: Help please!
note:i'm using bootstrap3
You need to write <?php tag at top of ajaxsubmit.php

Categories