How to insert data in database through jQuery Ajax in php - php

Hello stack right now I am facing a problem I am unable to insert data in database through jQuery Ajax I have attached all related files Can anyone go through it I am new in php development.
**task.php**
<html>
<head>
<style type="text/css">
html, body {
margin: 5px;
padding: 5px;
background: #fff;
}
form {
border: 1px solid #999;
padding: 0.25em;
background: #EEE;
}
div {
padding-bottom: 0.25em;
}
/* essential */
label {
float: left;
width: 6em;
text-align: right;
padding-right: 0.5em;
}
input, textarea {
text-align: left;
width: 200px;
height:30px;
}
input.submit {
margin-left: 6.5em;
width: auto;
}
label, input.submit {
font: normal 0.8em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
</style>
<script src="jquery-3.3.1.js"></script>
<script src="insert.js"></script>
<script>
</script>
</head>
<body>
<h1>FORM</h1>
<form>
<div>
<label>Name:</label>
<input type="text" name="name" id="Name" />
</div>
<div>
<label>Age:</label>
<input type="text" name="age" id="age"/>
</div>
<div>
<label>Email Id:</label>
<input type="text" name="emailId" id="emailId"/>
</div>
<div>
<label>Password:</label>
<input type="text" name="password" id="pass"/>
</div>
<div>
<input type="submit" id="submit" name="submit" value="Submit" onclick="insertData()" />
</div>
</form>
</body>
</html>
This is my insert.php file where I have write all query related to insert my data.
**insert.php**
<?php
include("connection.php");
if(isset($_POST['submit']))
{
$Fname=$_POST["name"];
$Age=$_POST["age"];
$EmailId=$_POST["emailId"];
$Password=$_POST["password"];
$Insert = "INSERT INTO simpleform (Name, Age, Email_Id, Password)
VALUES ('.$Fname.', '.$Age.', '.$EmailId.', '.$Password.')";
$Query=mysqli_query($con, $Insert);
print_r($Insert);
if(!$Query)
{
echo mysqli_error();
}
else
{
echo "Successfully Inserted <br />";
}
}
?>
This is my insert.js file where I did all ajax related work.
**insert.js**
function insertData() {
debugger;
var name=$("#Name").val();
var age=$("#age").val();
var emailId=$("#emailId").val();
var pass=$("#pass").val();
debugger;
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "kamalesh/insert.php",
data: {name:name,age:age,emailId:emailId,pass:pass},
dataType: "JSON",
success: function(data) {
alert("Data Inserted");
}
});
}

It looks like In your insert.php the if(isset($_POST['submit'])) is preventing the script from running when your insert.js function passes parameters to insert.php. When AJAX passes parameters to insert.php, the isset($_POST['submit']) will return false.
You will need to remove the if(isset($_POST['submit'])) from nsert.php. I will also suggest you to prevent the form from submitting and refreshing your page. Look into e.preventDefault.
Also for your $insert query you should remove the "." before and after each variable in the "VALUES". They are not needed.

Related

pass data to two fields

Hi I am trying to make a autocomplete function where I use a search field and write the first letters of the name of a company. the code vill search an online database for the company and there will be a list of suggestions. for example
company1 street1 zipcode etc.
company2 astreet2 zipcode etc.
company3 street1 zipcode etc.
I will click on one of the listed companies and it vill populate field1 with company1 field2 street field3 zipcode etc. but I cant make it. I dont reallt know how to do this and Im trying to learn and understand but this is too complex for me so I hope any of you guys can hekp me - thanks in advance.
This is how my code looks like so far.
main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="layout.css" rel="stylesheet" type="text/css">
<link href="menu.css" rel="stylesheet" type="text/css">
</head>
<style>
.kundsok {
border: 1px solid #a8d4b1;
background-color: #c6f7d0;
margin: 2px 0px;
padding: 40px;
border-radius: 4px;
}
#ftg-list {
float: center;
list-style: none;
margin- top: -3px;
padding: 0;
width: 190px;
}
#ftg-list li {
padding: 10px;
background: #f0f0f0;
border-bottom: #bbb9b9 1px solid;
}
#ftg-list li:hover {
background: #ece3d2;
cursor: pointer;
}
#search-box {
padding: 10px;
border: #a8d4b1 1px solid;
border-radius: 4px;
}
</style>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#search-box").keyup(function() {
$.ajax({
type: "POST",
url: "readkund_eniro.php",
data: 'keyword=' + $(this).val(),
beforeSend: function() {
$("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165 px ");
},
success: function(data) {
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background", "#FFF");
}
});
});
});
function selkund(val, val2) {
$("#search-box").val(val);
$("#foretag_name").val(val);
$("#stad").val(val2);
$("#suggesstion-box").hide();
}
</script>
<body>
<div id="sidlayout">
<div id="content">
<?php include "menukunder.php"; ?>
<div class="kundsok">
<center>
<input type="text" id="search-box" name ="search-box" placeholder="kund" >
<div id="suggesstion-box"></div>
</form>
<h1></h1>
<H3></H3>
<center>
<form action="sida3ka.php" method="post">
<fieldset>
<label title="Skriv in företagets namn" for="foretag_name">Företag:</label>
<input type="text" name="foretag_name" id="foretag_name">
<label title="Skriv in stad" for="stad">Stad:</label>
<input type="text" name="stad" id="stad">
</fieldset>
</form>
</div>
</div>
</body>
</html>
on the other page called readkund_eniro.php the code looks like this
$url = 'https://api.eniro.com/cs/search/basic?profile=Martens&key=3653823918839001013&country=se&version=1.1.3&search_word
=' . $_POST["keyword"] . '&geo_area=stockholm';
$response = file_get_contents($url);
$json = json_decode($response, true);
if(!empty($json)) {
?>
<ul id="ftg-list">
<?php
foreach($json['adverts'] as $ftg) {
?>
<li onClick="selkund('<?php
echo $ftg["companyInfo"]['companyName'];
echo $ftg["address"]['streetName'];
?>');"><?php
echo $ftg["companyInfo"]['companyName'];
?>
</li>
<?php
}
?>
</ul>
<?php
}
I the database respons will be
$ftg["companyInfo"]['companyName']
$ftg["address"]['streetName']
$ftg["address"]['postCode']
and so on. thanks again
Best regards Johan
i think there is problem in API url at readkund_eniro.php file. can you please try with as below.
$url = "https://api.eniro.com/cs/search/basic?profile=Martens&key=3653823918839001013&country=se&version=1.1.3&search_word=".$_POST['keyword']."&geo_area=stockholm";
another thing i found with your response text inside
<li onClick="selkund('<?php echo $ftg["companyInfo"]['companyName'];?>', '<?php echo $ftg["address"]['streetName'];?>');"><?php
echo $ftg["companyInfo"]['companyName']. ', '. $ftg["address"]['streetName'].', '. $ftg["address"]['postCode'] ;
?>
</li>

php login help for final project

So I am trying to make a valid login for my web dev class' final project. Whenever I try to log in with the correct credentials, I always get redirected to the "something.php" page, and I never receive any of the output that I put in my code. This even happens when I input valid login credentials.I know this isn't a secure way to do a login, but this is for final project purposes only. I've attached all of my files below (minus pictures), even though you probably don't need all of them.
The something.php file (the php for the login)
<?php
$action = empty($_POST['action']) ? false : $_POST['action'];
/*var radio = document.getElementById('radio');*/
switch ($action) {
case 'login':
$username = empty($_POST['username']) ? '' : $_POST['username'];
$password = empty($_POST['password']) ? '' : $_POST['password'];
if ($username=='test' && $password=='pass') {
setcookie('userid', $username);
$response = 'Login: Sucess';
}
else {
$response = 'Login: Fail';
}
print $response;
break;
case 'get':
$userid = empty($_COOKIE['userid']) ? '' : $_COOKIE['userid'];
if ($userid=='test') {
$response = 'Todays special are organic Brazilian strawberries $1.75 a pound';
}
if ($username!='test' || $password!='pass'){
header('Location: XXX/something.php');
echo "username and password combo are not valid";
//radio.value = "logged out";
}
print $response;
break;
case 'logout':
setcookie('userid', '', 1);
print 'Logged out';
break;
}
?>
login.html page
<div class="group">
<div id="radio">
<form id="radio" action="">
<input type="radio" name="select" value="login"> Logged In<br>
<input type="radio" name="select" value="logout" checked> Logged Out<br>
</form>
</div>
<form id="content2" class="itemBlock">
<p> Don't have an account? Sign up here!</p>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
E-mail: <br>
<input type="text" name="email"><br>
Password: <br>
<input type="text" name="password"><br>
<br>
<input type="button" value="Register" onclick="addToCartFxn()">
</form>
<div id="center">
<form id="content" class="itemBlock" action="something.php" method="post">
<br> <br>
E-mail: <br>
<input type="text" name="email"><br>
Password: <br>
<input type="password" name="password"><br>
<input type="submit" class="get" value="Login" id="login">
<input type="submit" value="Logout" id="logout">
</form>
</div>
</div>
final.php page
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tabs - Content via Ajax</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<!--<link rel="stylesheet" href="/resources/demos/style.css">-->
<!--<script src="jquery-1.10.2.min.js"></script>-->
<script>
$(function() {
$( "#tabs" ).tabs({
beforeLoad: function( event, ui ) {
ui.jqXHR.fail(function() {
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. ");
});
}
});
});
$(function(){
$('#login').click(function(){
$.post('something.php',
{
action: 'login',
username: $('#username').val(),
password: $('#password').val()
},
function(data){
$('#center').html(data);
});
});
$('#logout').click(function(){
$.post('something.php',
{
action: 'logout'
},
function(data){
$('#center').html(data);
});
});
$('.get').click(function(){
$.post('something.php',
{
action: 'get'
},
function(data){
$('#center').html(data);
});
});
});
function addToCartFxn() {
alert("This feature is coming soon!");
}
</script>
<style>
#floatright {
float:right;
}
#header{
background-image: url("tree rocks header.jpg");
width: 100%;
height: 200px;
padding-top: 1px;
text-align: center;
background-size: cover;
background-position-y: 3255px;
background-position-x: -2112px;
}
#headertext {
z-index: 100;
color: white;
font-size: 72px;
font-family: exo, arial, serif;
}
#font-face {
/* Declare the name of the font (we make this value up) */
font-family: exo;
/* And where it's located */
src: url("Exo-Medium.otf");
}
.addtocart{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 7px 12px;
border-radius: 7px;
text-align: center;
text-decoration: none;
font-size: 5px;
margin-bottom: 3px;
}
#radio {
float: right;
}
#content {
font-family: exo, arial, serif;
text-align: center;
border-radius: 25px;
background-color:forestgreen;
align-content: center;
}
#content2 {
font-family: exo, arial, serif;
float:left;
}
#logout{
margin: 5px;
}
#login{
margin: 5px;
}
.itemBlock{
display:inline-block;
margin: 10px;
border: 2px black;
border-style: solid;
text-align: left;
padding-left: 5px;
padding-right: 5px;
}
#font-face {
/* Declare the name of the font (we make this value up) */
font-family: exo;
/* And where it's located */
src: url("Exo-Medium.otf");
}
#center{
margin-left: 42%;
}
body {
min-height: 100%;
height: auto! important;
}
.group:after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div id="header">
<p id="headertext"> Claw's Cache</p>
</div>
<div id="tabs">
<ul>
<li> Our Products </li>
<li> Available Produce </li>
<li id="floatright"> Login</li><!--tabs-3's content is being put there by ajax-->
</ul>
<div id="tabs-1">
<p>Listed here are all the current vendors that are associated with us products.</p>
<?php
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob("*.png");
$i=0;
//Display image using foreach loop
foreach($images as $image){
echo '<div class="itemBlock"> <img src="'.$image.'" height="250" width="200" /> <br>';
echo '<button type="button" class="addtocart" onclick="addToCartFxn()"> add to cart</button> </div>';
}
?>
</div>
<div id="tabs-2">
<p>Our available produce page is being updated currently!
<br> <br> As a placeholder, we have attached a video that many of our customers recommend to every person interested in indoor gardening.</p><br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/RWCIaydwM_w" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</body>
</html>
At line
$action = empty($_POST['action']) ? false : $_POST['action'];
You read a POSTed form field called 'action'. I can't find that field in any of your web forms... Maybe give a name to your SUBMIT buttons are retrive that instead. Action is an atribute of the web form, not a field name.
it looks like it's ignoring your jquery login code because your form is submitting when you click Login, and since you're checking if $_POST['action'] is empty
$action = empty($_POST['action']) ? false : $_POST['action'];
it fails because you don't have any form element with that name. the form's action attribute only specifies to which page to send the data.
I think you might try adding onsubmit="return false" to your form in order to get it to only use your $.post method.
<form onsubmit="return false" id="content" class="itemBlock" action="something.php" method="post">
What happens if you amend your opening variable assignment to
empty($_POST['action']) ? $action = false : $action = $_POST['action'];
I'm not 100% sure why this happens, but I know from past experience that the shorthand IF statements can give some unexpected results.
On top of this, it doesn't look like you are setting the $_POST['action'] field anywhere?
If you are referring to the method of transmit specified in the opening <form> tag, then this is wrong.
If your shorthand IF statement is used to determine how data is being passed into the something.php file, then you could do
empty($_POST) ? (empty($_GET) ? echo "No User Data Passed" : $data = $_GET;) : $data = $_POST;
(I know it seems long winded, but the extra check for $_GET data can be omitted, it is simply there as a proof of concept type check).
From that, the $data variable will be set with either the $_GET or the $_POST user defined data from the forms on the other pages.
I hope this helps.

PHP & jQuery ajax Chat

I have created a chat application using PHP, mysql, and ajax for posting data to the server. I have tested it by spamming the chat repeatedly, and everything works for about 7 or 8 seconds until my chat will not post further. On refresh, I get a "NO DATA RECEIVED" error from google chrome. Basically I think I am overloading my site. Is there a way that I could optimize this chat? Or is it not a server-side issue at all?
This is my jQuery that is posting to my server:
$(document).ready(getMessage());
//Send message
$('#send').click(function() {
var message = $('#message').val();
var username = $('#un').val();
var id = $('#id').val();
var fullname = $('#name').val();
$.ajax({
url: 'chat/send_message.php',
type: 'POST',
data: {
message: message,
username: username,
user_id: id,
fullname: fullname
},
success: function() {
$('#message').val('');
getMessage();
}
});
return false;
});
function getMessage() {
$.post('chat/get_message.php', {getMessage: true}, function(message) {
$('#chatbox').html(message);
$('#chatbox').scrollTop($('#chatbox')[0].scrollHeight);
});
}
setInterval(getMessage, 5000);
This is the PHP that handles the sending of the message. It just stores it in a database:
<?php
//Message sending
if(isset($_POST['message'])) {
try {
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
} catch (PDOException $e) {
echo("Could not connect to the server.");
}
$message = $_POST['message'];
$timesent = date('Y-m-d H:i:s');
$id = $_POST['user_id'];
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$query = $pdo->prepare("INSERT INTO `message`(`message`,`user_id`,`timesent`,`fullname`,`username`) VALUES (:message,:user_id,:timesent,:fullname,:username)");
$query->execute(array(
':message' => $message,
':user_id' => $id,
':timesent' => $timesent,
':fullname' => $fullname,
':username' => $username,
));
} else {
echo("Could not send message");
}
This is my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><head>
<?php
include 'resources/head.php';
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
?>
<title>GoonSquad | Chat</title>
<style type="text/css">
form, p, span {
margin:0;
padding:0; }
input { font:12px arial; }
a {
color:#0000FF;
text-decoration:none; }
a:hover { text-decoration:underline; }
#wrapper {
margin:0 auto;
padding-bottom:0;
background: rgba(0, 0, 0, 0.13);
width: 1000px;;
border:1px solid #ACD8F0;
text-align: center;
}
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:400px;
width:940px;
border:1px solid #ACD8F0;
overflow:auto; }
#message {
width:860px;
border:1px solid #ACD8F0;
margin-right: 5px;
}
#submit { width: 60px; }
.error { color: #ff0000; }
#menu { padding:12.5px 25px 12.5px 25px; }
.welcome {
margin-left:auto;
margin-right: auto;
margin-top: 20px;
font-size: 150%;
}
.message {
width: 100%;
height: auto;
background-color: #cccccc;
margin-bottom: 6px;
border-radius: 3px;
padding: 6px;
}
.msgln { margin:0 0 2px 0; }
</style>
</head>
<body>
<?php include 'resources/header.php' ?>
<div id="row">
<div id="large-9 columns" class="override" role="content">
<div id="wrapper" class="left-align">
<div id="menu">
<p class="welcome">GoonSquad Chat</p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
</div>
<form id="messenger" action="" enctype="multipart/form-data">
<input type="text" id="message" class="left" autocomplete="off" size="63" maxlength="2000">
<input type="submit" id="send" class="button tiny" value="Send" >
<input type="hidden" id="id" value="<?php echo $user->data()->id; ?>">
<input type="hidden" id="name" value="<?php echo $user->data()->fullname?>">
<input type="hidden" id="un" value="<?php echo $user->data()->username?>"
</form>
</div>
</div>
</div>
<script type="text/javascript" src="scripts/chat.js"></script>
</body>
</html>

Creating a Auto Updating <div></div> When Information Was Pasted on Mysql

It's my first day here, I thought you guys could help me. So, I'm working on this kind of chatting service for a friend. I want it to auto update anything inside the div tags that has an id of messages. I tried adding some javascript and stuff from other posts, but they just made it worse. So, if anyone could fix it and comment, or give me suggestions. I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
<?php
session_start();
if(!isset($_SESSION['username']))
{
header("Location: /index.php");
}
?>
<html>
<head>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<?php
$connect = mysql_connect("localhost", "root", "*******");
mysql_select_db("*******");
$username = $_SESSION['username'];
$message = $_POST['message'];
$submit = $_POST['submit'];
if($submit)
{
if($message)
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
else
{
?>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<?php
}
}
?>
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" /> <br />
<br />
<input type="submit" name="submit" value="Submit" /> <br />
<br />
<?php
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div id="messages">
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div> <br />
<?php
}
}
else
{
?>
<center>
<error>There are no messages to display.</error> <br />
</center>
<br />
<?php
}
?>
</form>
</body>
</html>
I hope you guys can help me, thank you.
First create a page message.php as:
<?php
session_start();
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function()
{
//alert("hello");
// ss=document.getElementById("message").value;
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
});
});
</script>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" id="message" /> <br />
<br />
<input type="button" id="submit" name="submit" value="Submit" /> <br />
</form>
<br />
<div id="messages">
</div>
</body>
</html>
<script language="JavaScript"><!--
// v3 compatible:
function doSomething() {
// do something here...
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
setTimeout('doSomething()',3000);
}
setInterval('doSomething()',3000);
//--></script>
Then Create a page active.php as
<?php
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$username=$_SESSION['username'];
$message=$_POST['messages'];
if($message!="")
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC limit 1,0");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div>
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div>
<br />
<?php
}
}
else
{
echo"No message to show";
}
?>
This is very general chat.Now you need to change it according to your requirements.
I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
You will have to use javacript for that part. Everything else can be done with PHP and MySQL.
I watched great youtube tutorial the other day on how to do this. Its is a "quick and dirty" solution but should give you something to build on. http://www.youtube.com/watch?v=FyXeOX-uYMc

ajax autocomplete for multiple textbox

I have done autocomplete for my php code usign ajax.I used this code for autocompleting one fileld.Can I use the same code for autocompleting more than one field...
Code contains ajax code is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete.....</title>
<script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
<script type="text/javascript">
function lookup(inputString)
{
if(inputString.length == 0)
{
// Hide the suggestion box.
$('#suggestions').hide();
}
else
{
$.post("rpc.php", {queryString: ""+inputString+""}, function(data)
{
if(data.length >0)
{
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue)
{
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<style type="text/css">
body
{
font-family: Helvetica;
font-size: 11px;
color: #000;
}
h3
{
margin: 0px;
padding: 0px;
}
.suggestionsBox
{
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}
.suggestionList
{
margin: 0px;
padding: 0px;
}
.suggestionList li
{
margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}
.suggestionList li:hover
{
background-color: #659CD8;
}
</style>
</head>
<body>
<div>
<form>
<div>
Type your county:
<br />
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</form>
</div>
</body>
</html>
Code for database connection page is
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("name",$con);
if(!$con)
{
echo 'ERROR: Could not connect to the database.';
}
else
{
if(isset($_POST['queryString']))
{
$queryString = mysql_real_escape_string($_POST['queryString']);
if(strlen($queryString) >0)
{
$query = mysql_query("SELECT cname FROM country WHERE cname LIKE '$queryString%' LIMIT 10");
if($query)
{
while($result= mysql_fetch_object($query))
{
echo '<li onClick="fill(\''.$result->cname.'\');">'.$result->cname.'</li>';
}
}
else
{
echo 'ERROR: There was a problem with the query.';
}
}
else
{
// Dont do anything.
}
}
else
{
echo 'There should be no direct access to this script!';
}
}
?>
Yes, you can use the code to autocomplete more than one field.
The quick and dirty way:
HTML:
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill(this);" />
<input type="text" size="30" value="" id="inputString2" onkeyup="lookup(this.value);" onblur="fill(this);" />
<input type="text" size="30" value="" id="inputString3" onkeyup="lookup(this.value);" onblur="fill(this);" />
Javascript:
function fill(element,thisValue)
{
element.value = thisValue;
setTimeout("$('#suggestions').hide();", 200);
}
The jQuery and more efficient way (based on your jQuery version 1.2.1:
HTML:
<input type="text" size="30" value="" class="autoupdate" name="field1" />
<input type="text" size="30" value="" class="autoupdate" name="field2" />
<input type="text" size="30" value="" class="autoupdate" name="field3" />
Javascript (using jQuery 1.2.1):
// fill on blur!
$(".autoupdate").blur(function()
{
$(this).val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
});
// lookup value onkeyup!
$(".autoupdate").keypress(function()
{
var fieldvalue = $(this).val();
if ( fieldvalue.length > 0 )
{
// hide selections box
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+fieldvalue+""}, function(data)
{
if(data.length >0)
{
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
});
Further optimizations:
AJAXing a URL as you keypress is unnecessary. If you don't mind an extra second to auto-fill; it would be better to submit PHP forms onblur instead. Additionally, you can also take advantage of JSON and essentially get all the data you need in one single AJAX call which as a end result makes the form's footprint have 1 AJAX call and 1 MySQL database query. Otherwise, your simply pounding the server on each keyup event that is fired.
-- OR --
Alternatively you can setup a delay that waits 2-3 seconds before submitting the PHP form. It would then also need to ensure that the setTimeout is cleared upon additional keypresses so as to prevent unnecessary pileup of delayed AJAX calls.
So it all depends on your requirement, I dont see a need where autocomplete for one field will help with autocompleting another field in the same page.. Also, what are the chances that the user will enter the same string..
having said that you can be smart about it and store the response from your server in an associative array and check this associative array first before making a call to the sever to see if you can provide data from that, but for that I would recommend you store JSON data from the server and build the HTML using javascript (eg. templates). You can still store the html in the associative array but the html might change depending on your text box.
Code will probably look like this:
<script type="text/javascript">
var searchResults=[];
function lookup(inputString)
{
if(inputString.length == 0)
{
// Hide the suggestion box.
$('#suggestions').hide();
}
else if(searchResults[inputString])
{
$('#suggestions').show();
$('#autoSuggestionsList').html(searchResults[inputString]);
}
{
$.post("rpc.php", {queryString: ""+inputString+""}, function(data)
{
if(data.length >0)
{
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue)
{
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
Obviously you need to change your selectors/ or change the offset of the div etc based on which field you wanna give the autosuggest to.
Hope this helps.

Categories