Auto complete base on value of dropdown in database - php

I'm stuck with this problem with in a week. What I have here is dropdown select with ajax posting value to another dropdown but now I need to post into textbox with autocomplete function. What I need is connect my autocomplete query and my ajax so that if I select for example ballpen, all ballpen will recommend in autocomplete. Please Help me with this. I need to finish it.
Here's my code
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
In here I post the value in another dropdown but not I need to post into textbox.
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
autocomplete.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>

//whenever u select the tag field will get focus, and it automatically start searching so u no need to type see the callback focus function with $(this).autocomplete("search", ""); and minlength 0. u have to send the main value and get the response from here too
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
untested, if any question post comment

Related

How to check whether a text variable is equal to an Array

My requirement is to check whether a text variable is equal or not to an mysql output array.
The mysql output array I have taken as follows,
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$('#book_name').val()=$book_required;
if(in_array($book_required,$avail_books))
{
alert("Not Available");
}
else{
$.ajax({
url:"books.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
}
}
But this is not working. Can someone show where I have messed this?
There can be other ways to accomplish what you want.
For example, use the following query:
SELECT count(*) FROM takenbooks where book_name = ?
But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believe is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)
For the HTML
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: 'checkdata.php',
data: {data1: $('#book_name').val()},
success: function(data){
alert(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
})
})
</script>
For the PHP (checkdata.php)
<?php
if (isset($_POST["data1"])){
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
if(in_array($_POST["data1"],$avail_books)) {
echo "Not Available";
} else {
// Place insert query here
echo "New Record inserted";
}
}
?>
You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)
<?php
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
Book name: <input type="text" name="book_name">
<input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>
const avail_books = <?php json_encode($avail_books); ?>;
document.querySelector('#insert_form').addEventListener(function (evt) {
evt.preventDefault();
let book_name = evt.target.book_name.value;
let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
document.querySelector('#available').innerHTML = book_name + " is " + not_available + " available.";
});
</script>
</body>
</html>
PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.
Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:
const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];
With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.
It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.
<html>
<body>
<form action="" method="POST">
<input type="text" name"book" required placeholder="Type the name of the Book" />
<input type="submit" value="Search Book" />
</form>
<div><h2>Results:</h2>
<?php
if(isset($_POST['book'] && !empty($_POST['book'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli("localhost", "root", "", "newbooks");
$stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
$stmt->bind_param("s", "%" + $_POST['book'] + "%");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
}
}
?>
</div>
</body>
</html>

Getting value from database using jquery on change event

I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>
Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS
Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.

get data from database using ajax not working

i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});

Ajax post value and store in php variable

I have here a ajax. What I need to know if it possible to send back the post value and store it in php variable in the mainpage depending in onchange event? $_POST["mainlist_id"] store in php var?
getajax.php
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>
getajax.php
<?php
session_start();
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$_SESSION['mainlist_id']=$main;
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<?php session_start();
$main_id=$_SESSION['mainlist_id'];
?>
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>

using JQuery with mySQL confusion

HI,
I have code like this. what I am doing is populating the first select with the MySQL data and based on the selection the first , using jQuery, I am populating the second one. Now, my question is, can I use the same combos_get.php to populate the another select based on user selection from the second select?
Is yes, then please look at the comment 'stuck at this point' where I am confused on how to get the data on the the third select.
<html>
<head>
<link href="style23.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title></title>
</head>
<body>
<div align="left" style="position:absolute;top:10px;">
<select name="select1" id="select1" size="10px;">
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select * from results where ID NOT LIKE 'Ex%' ") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array( $result )) {
// Print out the contents of the entry
?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['ID'] ?></option>
<?php
}
?>
</select><br>
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
// $('#select2').change(getDropdownOptions); // stuck at this point
});
function getDropdownOptions() {
var val = $(this).val();
//alert(val);
// fire a POST request to combos_get.php
$.post('combos_get.php', { value : val }, populateDropdown, 'html');
//alert('s');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
</div>
<div align="left" style="position:relative;left:250px;">
<select name="select2" size="10px;" id="select2">
<option value="--">--</option>
</select>
</div>
<div style="position:relative;left:450px;top:10px">
<select name="select3" size="10px;" id="select3">
<option value="--">--</option>
</select>
</div>
</body>
</html>
**combos_get.php**
<?php
if (!empty($_POST['value'])) {
$val = $_POST['value'];
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select ID2 from results where ID = \"$val\" ") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$html .= '<option value="1">'.$row['ID2'].'</option>';
}
die($html);
}
die('error');
?>
You will more than likely want another handler for this case. It's up to you whether or not the same PHP file can handle the query, however:
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
$('#select2').change(getSecondDropdownOptions);
});
function getSecondDropdownOptions() {
var val = $(this).val();
$.post('combos_get.php', { value : val }, populateSecondDropdown, 'html');
}
function populateSecondDropdown(data) {
if (data != 'error') {
$('#YOURNEXTSELECT').html(data);
}
}
Common practice is to reuse as much code as possible. I don't have time to refactor since I just got to work but someone is more than welcome to clean this up for him.
In order to do that you need to make populateDropdown use a dynamic target.
something like:
function getDropdownOptions(event) {
var e = $(this);
var val = e.val();
// fire a POST request to combos_get.php
$.post('combos_get.php',{ value : val }, function(data){
populateDropdowns(data, e);
}, 'html');
}
function populateDropdown(data, e) {
// e is our originating select
/* HERE You need to come up with a way to determin the target to populate based on the element that triggered it. for example assuming you only have 3 selects:*/
switch(e.attr(id)){
case 'select2':
var targetSelector = '#select3';
break;
case 'select1':
var targetSelector = '#select2';
break;
default:
var targetSelector = null;
break;
}
if (data != 'error' && targetSelector) {
$(targetSelector).html(data);
}
}

Categories