Autocomplete jQuery with mysql database's data - php

I created this jquery autocomplete but as a result it returns [].
In the users table there are 2 fields: "ID" (int autoincrement) and "Name (varchar)" and are populated.
auto_complete_jquery.html:
<html>
<head>
<title><!-- Insert your title here --></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<script>
$(function() {
$("#tags").autocomplete({source: "name.php", dataType: 'json'});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
connection.php:
<?php
$hostname="localhost";
$username="root";
$password="";
$conn=mysql_connect($hostname,$username,$password);
$dbs = mysql_select_db("jquery_test",$conn);
if(!$conn)
{
echo("Error connection MySQL.");
exit();
}
?>
name.php:
<?php
$return_arr = array();
$term = $_GET["term"];
include "connection.php";
$result= mysql_query("SELECT * FROM users WHERE MATCH(Name) AGAINST('".$term."*')") or die (mysql_error());
?>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$row_array['value'] = $row['tagName'];
array_push($return_arr,$row_array);
}
mysql_close($conn);
$json=json_encode($return_arr);
echo $json;
?>

Hope you looking for this,
$( "#PopulateData" ).autocomplete({
minLength:2,
delay: 50,
selectFirst: true,
open: function () {
$(this).data("autocomplete").menu.element.width(409);
},
source:function(request,response){
removeConflict.ajax({
url: 'remotefile.php?list='+$('#PopulateData').val(),
data: request,
dataType: null,
type: "GET",
success: function(data){
var listarray= jQuery.parseJSON(data);
response(
$.map(listarray, function(item) {
var text = item.jsonpropertyA;
var code = item.jsonpropertyb;
console.log(text )
return {
label: code,
value: text
}
})
)},
error:function(data){
console.log(data)
}
});
},
select: function( event, ui ) {
console.log('value:'+ ui.item.value + ',label:'+ui.item.label);
}
});
json object is returned from the server response, and the label and value is returned to the autocomplete text box.
Note: you've can do some modification which suites your. :)

Related

AJAX load to another div with variable

Hey Im trying to load another div with passing variable.
Im in the div#main , I want a after click #modifybtn button pass the btn value and load it with another div#modify and working with some query.
im noob for jQuery and ajax, I search in web but cant get solution for this.
please check relevant code and tell me about issue.
here is the div#main #modifybtn button and div#modify
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
</div>
<div id="modify">
<?php
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='{$_GET['id']}' LIMIT 1 ");
?>
</div>
dashcompany.php inside
<div class="contentcm" >
//contentcm.php page load content here
</div>
this is my jQuery, after clicking button alert showing but not redirect to the #modify div
$(document).ready(function(){
$('.contentcm').load('contentcm.php #main');
$('a').click(function(){ //main and modify division in contentcm.php
var clickedLink1 = $(this).attr('id');
$('.contentcm').load('contentcm.php #' + clickedLink1);
});
});
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
});
This will be initial.html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src = "FILE_NAME.js"></script>
</head>
<body>
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
<div id="modify"></div>
</div>
</body>
</html>
Your code in FILE_NAME.js should be like
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
Your js file will load the data from dashcompany.php and load in #modify which is in initial.html file
dashcompany.php
<?php
include_once('connection.php');
$id = $_GET['id'];
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='$id' LIMIT 1 ");
$row = $resultmodi->fetch_assoc();
echo "Name: " . $row["name"];
''' print data whatever you need '''
$conn->close();
?>
REASON:
May be you forgot to print data in dashcompany.php file that's why you are getting blank response from ajax request.
And don't forget to include #modify div in the same html file where #main#modify div exists
You can use as follow code, and I suggest you to use post method
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type='button' id="modifybtn" class='btn btn-info' value="some_value">click here</button>
<div class="" id="modify"></div>
<script type="text/javascript">
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
//alert(id);
$.ajax({
url: 'dashcompany.php',
type: 'post',
data: {'id' : id},
dataType: 'json',
success: function(response) {
//now you can call with column name of data table
$('#modify').html("<P>"+response.column_one_name+"</p><br><P>"+response.column_two_name+"</p>");
}
});
});
</script>
And your dashcompany.php page should like this,
<?php
// $localhost = "127.0.0.1";
// $username = "root";
// $password = "";
// $dbname = "db_304";
//
// $connect = new mysqli($localhost, $username, $password, $dbname);
// // check connection
// if ($connect->connect_error) {
// die("Connection Failed : " . $connect->connect_error);
// }
$id = $_POST['id'];
$sql = "SELECT * FROM vacancy WHERE vc_id = '$id' LIMIT 1 ";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
Hope this will help you.

getting all html in the console trying ajax call with autocomplete

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en-us">
<title>PHP MySQL Typeahead Autocomplete</title>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
/*$( "#skills" ).autocomplete({
source: 'singleton.php'
});*/
$("#skills").keyup(function(){
$.ajax({
type: 'post',
url: 'singleton.php/',
data: 'term='+$(this).val(),
success: function(success){
$("#suggesstion-box").html(data);
},
error: function(error){
console.log("error");
}
})
})
});
</script>
</script>
<?php
/*include_once('connection.php');
$conn = new Database();*/
$hostname = "localhost";
$username = "root";
$password = "";
$databasae = "employee";
if(isset($_POST['term'])){
$query = $_POST['term'];
$db = new mysqli($hostname,$username,$password,$databasae);
//get search term
$searchTerm = $_POST['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM city WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
}
?>
<div class="ui-widget">
Enter City Name:
<input type="text" name="city" class="city" id="skills" placeholder="Enter City Name" id="city">
<div id="suggesstion-box"></div>
</div>
</body>
</html>
I'm getting correct value in the network but it does not populating data in suggestion-box div.
I can't figure out where i'm mistaking.
Is it possible that you accidentally replaced 'data' with 'success' in the 'success' callback?
$("#skills").keyup(function(){
$.ajax({
type: 'post',
url: 'singleton.php/',
data: 'term='+$(this).val(),
success: function(success){
$("#suggesstion-box").html(data);
},
error: function(error){
console.log("error");
}
})
})
Should't it be
success: function(data) {
$("#suggesstion-box").html(data);
}
?

Customizing drop down list with ajax

I'm trying to extract data from my database to drop_down_list1 through ajax. and display it to the next drop_down_list2. I follow almost exact same thing like in this youtube tutorial but it seems not working.
Here's the code:
test.php
<?php
include("connection.php");
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/JavaScript">
function State(){
$('#stateddl').empty();
$('#stateddl').append("<option>Loading...</option>");
$('#districtddl').append("<option value='0'> - </option>");
$.ajax({
type:"POST",
url:"custom2.php",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
$('#stateddl').empty();
$('#stateddl').append("<option value='0'>-</option>");
$.each(data,function(i,item){
$('#stateddl').append('<option value="'+ data[i].roomName +'">'+ data[i].roomName+'</option>');
});
},
complete: function(){
}
});
}
function District(sid){
$('#districtddl').empty();
$('#districtddl').append("<option>Loading...</option>");
$.ajax({
type:"POST",
url:"custom.php?sid="+sid,
contentType:"application/json; charset=utf-8",
dataType="json",
success: function(data){
$('#districtddl').empty();
$('#districtddl').append("<option value='0'> - </option>");
$.each(data,function(i,item){
$('#districtddl').append('<option value="'+ data[i].roomPrice +'">'+ data[i].roomPrice +'</option>');
});
},
complete: function(){
}
});
}
$(document).ready(function(){
State();
$("#stateddl").change(function(){
var roomName = $("#stateddl").val();
District(roomName);
});
});
</script>
</head>
<body>
<select name="stateddl" id="stateddl"></select> <select name="districtddl" id="districtddl"></select>
</body>
</html>
custom2.php
<?php
include("connection.php");
$sql=mysql_query("SELECT * FROM roomtype");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[] = array
(
'roomName' => $row['roomName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
custom.php
<?php
include("connection.php");
$sql=mysql_query("SELECT * FROM roomtype WHERE roomName='".$_GET["sid"]."'");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[] = array
(
'sid' => $row['roomName'],
'roomPrice' => $row['roomPrice']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
The problem is because of following function block,
function District(sid){
...
$.ajax({
...
dataType="json",
...
});
}
See the dataType setting of the AJAX request, wrong = sign. It should be dataType:"json"

How to fill data of PostgreSQL into combobox using jquery ajax and php

I want to fetch data from PostgreSQL into my Combobox using query Ajax in html page.
Here is the code of popup box where I want to fetch the data:
<html>
<body>
<script src="../webmap/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function dropdown(){
$('#a1_title').empty();
$('#a1_title').append("<option>loading....</option>");
$.ajax({
type: "POST",
url: "drpdwn.php",
contentype: "application/json; charset=utf-8",
dataType: "json",
sucess:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option value='0' >----select name-</option>");
$.each(data,function(i,item){
$('#a1_title').append('<option value="'+ data[i].id +'" >'+ data[i].name +'</option>');
});
},
complete: function(){
}
});
}
$(document).ready(function(){
dropdown();
});
</script>
<select id="a1_title">
</select>
</body>
</html>
This is drpdwn.php file:
<?php
$host = "localhost";
$user = "postgres";
$pass = "admin";
$db = "Querybuilderdb";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT id, name FROM tab";
$result = pg_query($con, $query);
if(pg_num_rows($result)){
$data=array();
while($row=pg_fetch_array($result))
{ $data[] = array(
'id'=>$row['id'],
'name' =>$row['name']
);
}
echo json_encode($data);
}
?>
I have update my code here Can anyone please tell me where i'm doing wrong?
Why don't you simply echo out the results?
<?php
$query = "select distinct levelone as Name from tab limit 1";
$res = pg_query($con, $query)
?>
<select name="dbname" id="dbname" >
<?php
while $row = pg_fetch_assoc($res) {
echo "<option>" . $row['levelone'] . "</option>";
}
?>
<select>
Usually what I do is rather than using two files why not echo the entire file from the PHP script thus the page loads when the result is returned from your query?
Its working now by using getJSON
<html><body>
<select id="a1_title">
</select>
<select id="a2_title">
</select>
<script src="jquery-2.0.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("drpdwn.php", success = function(data){
var items="";
for(var i = 0; i< data.length; i++){
items +="<option value='"+ data[i].toLowerCase() +"'>" + data[i] +"</option>";
}
$("#a1_title").append(items);
$("#a1_title").change();
});
$("#a1_title").change(function(){
$("#a2_title").html("");
$.getJSON("second_dropdown.php?tabs="+ $(this).val(),success = function(data){
alert("okay");
var items="";
for(var i = 0; i< data.length; i++){
items+="<option value='"+data[i].toLowerCase()+"'>"+data[i]+"</option>";
}
$("#a2_title").append(items);
});
});
});
</script>
</body>
</html>

Enable Android App to Connect to the Internet

I have created a simple app using Phohegap to retrieve few records frm a remote database using the following index.html:
<!doctype html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script charset="utf−8" type="text/javascript">
function connect(e)
{
var term= {button:e};
$.ajax({
url:'http://dubaisinan.host22.com/reply.php',
type:'POST',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
alert("No Connection");},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center><input onclick="connect(this.value)" type="button" value="showStudents" /></center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
And the following reply.php:
<?php
header('Content-Type: application/json');
$link = mysql_connect('host_name', 'user-name', 'password');
if (!$link)
{
$myStudents[] = "No";
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2808249_db1",$link);
$result = mysql_query("SELECT * FROM Students",$link);
while ($myrow = mysql_fetch_row($result))
{
$myStudents[] = $myrow[1];
}
print json_encode($myStudents);
?>
It works fine on my laptop but when I build it using Phonegap and download the apk file on my Note 3 device, I receive the message "No Connection". It seems that the app is not able to connect to the Internet. The device has Internet connection.
Any help please?
Sinan
Add these lines
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
Also you said you want to retrieve, so this should be a GET call , not POST.
Also use <!DOCTYPE html> (proper coding standard)
Edit : Example GET call
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "GET",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
EDIT : This is a sample code which can POST to a test server
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="javascript" type="text/javascript">
<!--
function greeter() {
var accx = 5;
var accy = 6;
var accz = 7;
var output = [];
output[0] = {
name: "Accel_X",
value: accx.toString(), // retrieve x
};
output[1] = {
name: "Accel_Y",
value: accy.toString(), // retrieve y
};
output[2] = {
name: "Accel_Z",
value: accz.toString() // retrieve z
};
var fromData = {};
fromData.output = output;
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
jQuery.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
data: fromDatan,
dataType: "JSON",
success: function(fromDatan, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
/*
error:function(jqXHR,text_status,strError){
alert("No Connection");},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}*/
});
return false;
}
//-->
</script>
</head>
<body>
<button onclick="greeter();">Click me</button>
</body>
</html>
I tried with your url, not working. However will let you know if I can

Categories