How to add onkeypress save in php form - javascript

**This is my php index.php file. I want to type first name and last name type and auto it has to be save the database. I wrote the code using ajax. but, this is not working properly. Please can any one help me. **
index.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script type="text/javascript">
$(document).on('keyup','firstName','lastName',function(){
var rel = $(this).attr('rel');
var flatvalue = $(this).val();
$("#firstName"+rel).val(flatvalue);
});
</script>
</head>
<body>
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
</body>
</html>

onKeyPress event not proper because it call many times as per user hit.
Use onBlur event instead of onKeyPress for submit the form and save it to MySql users table.
Try below example,
PHP
<?php
$connection = mysql_connect("localhost", "jaydeep_mor", "jaydeep_mor");
$db = mysql_select_db("jaydeep_mor", $connection);
if(isset($_POST['firstName']) && isset($_POST['lastName'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName != '' || $lastName != ''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
header("Location: test.php?msg=Data Inserted successfully...!!");
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
HTML / JAVASCRIPT
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta><title>Home Page</title>
<script type="text/javascript">
function saveData(){
document.forms["userDataForm"].submit();
}
</script>
</head>
<body>
<?php if(isset($_GET['msg']) && trim($_GET['msg'])!=""){ ?>
<br /><div><?php echo $_GET['msg']; ?></div><br />
<?php } ?>
<form action="test.php" method="post" name="userDataForm">
<label for="firstName">First Name</label>
<input type="text" name="firstName" value="<?php echo isset($_POST['firstName'])?$_POST['firstName']:''; ?>" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" value="<?php echo isset($_POST['lastName'])?$_POST['lastName']:''; ?>" onblur="return saveData();" ><br><br>
<!--input type="submit" id="Submit" name="Submit" value="submit"/-->
</form>
</body>
</html>

<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_REQUEST['firstName'])){
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
die();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
die();
}
}
//mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){ alert('d');
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url:'',
data:{'firstname':firstname,'lastname':lastname, },
type: 'POST',
success: function(data){
alert("Data Save: " + data);
}
});
});
});
</script>
</head>
<body>
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName"><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName"><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</body>
</html>

may be this can help you,
if you want to do it via form submit then just you need to give the url of your controller function in the action method of the form
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
if you want to do it via ajax then you can add id attribute for first_name and last_name input and can do it in following way,
$('#submit').on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: url of your controler, //url of your controller function
type: "POST",
data: {'first_name' : first_name,'last_name':last_name},
success: function (data) {
//whatever you want to do on success
} else {
//in case of no data
}
}
});
});
in the same way you can give a class attribute to the input box and on keyup event can save the data via class

have you try doing it this way
$('body').delegate('input[type="text"]', 'keypress keydown keyup change propertychange paste', function(event) {
event.stopImmediatePropagation();
if (event.type === 'keydown' || event.type === 'keypress') {
return;
}
//insert what you want to do here
//perform some ajax
/*
$.ajax({
url: 'index.php',
method: 'POST',
data: {
'firstName' : $('input[name=firstName]).val(),
'lastName' : $('input[name=lastName]).val()
},
success: function(mResponse) {
alert(mResponse);
}
});
*/
});

Related

How to copy a file then rename it based on input field via buttonclick?

Good day experts!
I want to copy a file and rename it based on input value via button click. MY code is not working. There is no file being copied nor being renamed.
Here's my code:
<?php
error_reporting(0);
if($_POST['action'] == 'call_this') {
echo Success!;
};
$file = 'data.php';
$newfile = '$_GET['subject'].php';
echo copy($file, $newfile);
?>
<form action="<?php echo $newfile ?>" method="get">
<input type="text" name="subject" required>
<button type="submit">Change</button>
</form>
<script>
function change() {
$.ajax({
type: "POST",
url: 'data.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
</script>
i think this is what you looking for:
<html>
<body>
<form method="post" action="copy.php">
<input type="text" placeholder="new name" name="newFileName"/>
<input type="submit" value="Change"/>
</form>
</body>
</html>
copy.php :
<?php
$file = 'sample.txt';
$newfile = $_POST["newFileName"].'.txt';
if (!copy($file, $newfile)) {
echo "failed to copy";
}else {
echo "copy with new name";
}
?>

Undefined Index error php (Submit tag doesn't enter the information in mysql table)

I have to enter the data from a form to a database table. I created the test database and the employee table in phpMyAdmin. When I run it on localhost I get the undefined index error for variables Name, Surname..., and the submit tag doesn't upload the form info into the table in the database. How can I solve this problem?
This is my code:
page.php
<?php
include_once('db.php');
$sql = " ";
$vlere = mysqli_query($sql,$conn);
if (isset($_POST['submit'])) {
$Name = $_POST['name'];
$Surname = $_POST['surname'];
$Birthday = $_POST['birthday'];
$Email = $_POST['email'];
$Telephone = $_POST['telephone'];
$Address = $_POST['address'];
$Company = $_POST['company'];
$Role = $_POST['role'];
$sql = "INSERT INTO employee(Name, Surname, Birthday, Email, Telephone, Address, Company, Role) VALUES('$Name', '$Surname', '$Birthday', '$Email', '$Telephone', '$Address', '$Company', '$Role')";
$vlere = mysqli_query($sql,$conn);
}
if (!empty($vlere)) {
echo "Empty";
}
else {
echo "Inserted";
}
?>
index.html
<html>
<head>
<title>Human Resource</title>
</head>
<body>
<h3><center>Enter the <b>EMPLOYEE</b> information</center></h3>
<form action="page.php" method="post">
Name:
<input type="text" name="name" ></br></br>
Surname:
<input type="text" name="surname" ></br></br>
<div>
Birthday:
<input type="date" name="birthday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"/>
</div>
</br></br>
<div>
Email:
<input type="email" name="email" size="40" maxLength="40" required placeholder="username#gmail.com" pattern=".+#gmail.com">
</div>
</br></br>
<div>
Telephone:
<input type="tel" name="telephone" max="15" required placeholder="xxx-xxx-xxxx" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
</div>
</br></br>
<div>
Address: <input type="address" name="address" required />
</div>
</br></br>
Company Name:
<form>
<select id="company">
<option value="AT Consulting">AT Consulting</option>
<option value="IKUB.al">IKUB.al</option>
<option value="InfoSoft">InfoSoft</option>
<option value="ATOM Computers">ATOM Computers</option>
</select>
</form>
Field:
<input type="text" id="field" />
<button onclick="func1()">Add</button>
<script>
function func1(){
var x = document.getElementById("company");
var option = document.createElement("option");
option.innerHTML = document.getElementById("field").value;
x.add(option);
}
</script>
</br></br>
Role: <input type="text" name="role" >
</br></br>
<input type="submit" name="submit" value="submit" />
</form>
<script src="script/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="script/first_script.js" type="text/javascript"></script>
</body>
first_script.js
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function() {
return false;
});
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
db.php
<?php
$conn = mysqli_connect('localhost', 'root', '');
$db = mysqli_select_db('test');
?>
Thank you for taking your time to answer me.

Ajax submitting form without refreshing page [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
Can anyone tell me why this bit of code isn't working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
</body>
</html>
When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out
The form is submitting after the ajax request.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
JS Code
$("#submit").click(function() {
//get input field values
var name = $('#name').val();
var email = $('#email').val();
var message = $('#comment').val();
var flag = true;
/********validate all our form fields***********/
/* Name field validation */
if(name==""){
$('#name').css('border-color','red');
flag = false;
}
/* email field validation */
if(email==""){
$('#email').css('border-color','red');
flag = false;
}
/* message field validation */
if(message=="") {
$('#comment').css('border-color','red');
flag = false;
}
/********Validation end here ****/
/* If all are ok then we send ajax request to email_send.php *******/
if(flag)
{
$.ajax({
type: 'post',
url: "email_send.php",
dataType: 'json',
data: 'username='+name+'&useremail='+email+'&message='+message,
beforeSend: function() {
$('#submit').attr('disabled', true);
$('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#submit').attr('disabled', false);
$('.wait').remove();
},
success: function(data)
{
if(data.type == 'error')
{
output = '<div class="error">'+data.text+'</div>';
}else{
output = '<div class="success">'+data.text+'</div>';
$('input[type=text]').val('');
$('#contactform textarea').val('');
}
$("#result").hide().html(output).slideDown();
}
});
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() {
$("#contactform input, #contactform textarea").css('border-color','');
$("#result").slideUp();
});
HTML Form
<div class="cover">
<div id="result"></div>
<div id="contactform">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="Yourname" type="text">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="admin#admin.com" type="text">
<p class="contact"><label for="comment">Your Message</label></p>
<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
PHP Code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
$output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
$output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if (strlen($message) < 5) { //check emtpy message
$output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
die($output);
}
$to = "info#wearecoders.net"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
'Reply-To: ' . $useremail . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to, $subject, $message . ' -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
$output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
die($output);
} else {
$output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
die($output);
}
This page has a simpler example
http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location.
Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
type="button"
should be
type="submit"
In event handling, pass the object of event to the function and then add statement i.e.
event.preventDefault();
This will pass data to webpage without refreshing it.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(function () {
$(".submit").click(function (event) {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time=' + time + '&date=' + date;
console.log(dataString);
if (time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#data").html(data);
}
});
}
event.preventDefault();
});
});
</script>
<form action="post.php" method="POST">
<input id="time" value=""><br>
<input id="date" value=""><br>
<input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
<?php
print_r($_POST);
if ($_POST['date']) {
$date = $_POST['date'];
$time = $_POST['time'];
echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {
}
?>

ajax form request still reloads page

I am trying to submit a form using ajax with jquery mobile without it refreshing the page and am having no luck..
I have this form -
index.php:
<script>
function SubmitForm() {
var name = $("#name").val();
$.post("bump.php", { name: name},
function(data) {
//alert(data);
});
}
</script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Here is bump.php
$date = date('y/m/d H:i:s');
$id = $_POST['name'];
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
I would like to maintain my position on the page but it refreshes each time? What am I doing wrong here?
Use event.preventDefault(); Cancels the event if it is cancelable, without stopping further propagation of the event.
Default behaviour of type="image" is to submit the form hence page is unloaded
function SubmitForm(event) {
event.preventDefault();
var name = $("#name").val();
$.post("bump.php", {
name: name
},
function(data) {
//alert(data);
});
}
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm(event);" value="Send" />
</form>
user return false in onclick`
function SubmitForm() {
//event.preventDefault();
var name = $("#name").val();
console.log(name);
$.post("message.html", { name: name},
function(data) {
alert(data);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="http://switchon.global2.vic.edu.au/files/2015/07/4x5-1jroh2i.png" id="searchForm" onclick="SubmitForm(); return false;" value="Send" />
</form>

Get two terms (values) from a form in AJAX

I want to run an AJAX script witch queries my database based on two parameters.
That is the form I've got
<form id="search-box" action="search.php" method="post">
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" id="username" name="username" size="31" placeholder="username ..." />
/
<input type="text" id="surname" name="surname" size="31" placeholder="surname..." />
<input type="submit" id="submit-button" name="sa" value="search" />
</form>
That is the java script for the AJAX:
<script type="text/javascript">
$(function() {
$("#surname").autocomplete({
source: "ajax-user.php",
minLength: 2,
});
});
</script>
And that is the php for the which does the query
<?php
require_once('connection.php');
try {
$conn = new readPDO("test");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$ac_term2 = "%".$_GET['term2']."%";
$query = "
SELECT
surname
FROM
worker
WHERE
lower(username)
LIKE lower(:term)
AND
lower(surname)
LIKE lower(:term2)
";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->bindValue(":term2",$ac_term2);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['repoName'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what I was not able to do is to get $ac_term2 value passed. Any suggestions?

Categories

Resources