I am trying to make my autocomplete search work but when i try to get data from my json array it doesnt work. I am not so familiar with this, but this is how my code looks like. I think I know how the first file works but I don't get it how my "searchapi.php" is going to be wrote. And what is this $.map? Would be great if someone could explain :D Thank you
index.php:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
#city { width: 15em; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table(?), function( item ) {
return {
label: item.name,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
searchapi.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$value = #$_POST['name_startsWith'];
$data = ("select name from column where name LIKE '".$value."'");
$result = mysql_query($data);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
?>
The searchapi.php file purely queries your database for like entries based upon the string (name_startsWith) being sent by the autocomplete function.
The $.map is a jQuery method for translating "all items in an array or object to new array of items." You can read about it here: http://api.jquery.com/jQuery.map/
Related
I'm trying to fill an autocomplete with the result of a mysql query and the options never show up, but I'm getting the json response correctly. I tried to change the z-index in my master css file and in the jquery-ui.css but it doesn't work.
This is my jquery function.
$('#tasklist').autocomplete({
source: function(request, response) {
$.ajax({
url: 'pruebaproy.php',
type: 'GET',
data: {term: request.term},
success: function(data) {
response( $.map( data, function ( item ) {
return item;
}));
}
});
},
minLength: 2,
focus: function( event, ui ) {
$('#tasklist').val( ui.item.nombre );
return false;
}
});
This is my PHP function that does the mysql query:
public function showTasks($term) {
include 'Conexion.php';
$conectar = new Conexion();
$arr_res = array();
$consulta = "SELECT * FROM Actividades WHERE nombre LIKE '%".$term."%'";
if($stmt = $conectar->open()->query($consulta)) {
while($row = $stmt->fetch_array(MYSQL_ASSOC)) {
$task['id'] = utf8_encode($row['idActividades']);
$task['nombre'] = utf8_encode($row['nombre']);
$task['cat'] = utf8_encode($row['parteAsoc']);
array_push($arr_res, $task);
}
echo json_encode($arr_res);
}
$stmt->close();
}
And I call this function in my 'pruebaproy.php'
include('Proyecto.class.php');
$proyect = new Proyecto();
if(isset($_GET['term'])) {
$proyect->showTasks(trim(strip_tags($_GET['term'])));
}
Try changing the datatype to 'json' on the ajax request, and place some alerts along the code to validate if you're getting there (for example inside the success).
$( "#city" ).autocomplete({
source: function( request,response ) {
$.ajax({
url: "dtautocomplete.php",
dataType: "json",
data: {term: request.term},
success: function( data) {
response( data.myData );
}
});
},
select: function( ) {
$( "#city" ).attr("selectflag","1");
}
});
Php side
<?php
//die("sleeeeeeeeeeeeeeeppppppppppppppppppppppppppppppppppppppppppppppp");
$term=$_GET['term'];
$query="SELECT `RegionName`, `CenterLatitude`,`CenterLongitude` FROM `regioncentercoordinateslist` WHERE `RegionName` LIKE '".$term."%' AND `RegionName` NOT LIKE '%type%' LIMIT 10";
// echo $query;
$data= mysql_query($query);
//var_dump($data);die();
$count=0;
while($dat=mysql_fetch_array($data))
{
if($count>12)
{break;}
$tmpt1=$dat['CenterLatitude'];
$tmpt2=$dat['CenterLongitude'];
$tmpt=$tmpt1.",".$tmpt2;
$city[] = array(
'label' =>$dat['RegionName'],
'value' => $tmpt
);
$city2[] = $dat['RegionName'];
$options['myData'][] = array(
'label' =>$dat['RegionName'],
'value' => $dat['RegionName']
);
$name=$dat['RegionName'];
// echo "<div>$name</div>";
$count++;
}
echo json_encode($options);
//flush();
?>
Try utilizing ._renderItem . See Custom data and display "viewsource"
$('#tasklist').autocomplete({
source: function(request, response) {
$.ajax({
url: 'pruebaproy.php',
type: 'GET',
data: {term: request.term},
success: function(data) {
response( $.map( data, function ( item ) {
return item
})
}
});
},
minLength: 2,
focus: function( event, ui ) {
$('#tasklist').val( ui.item.nombre );
return false;
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.id + "<br>" + item.cat + "</a>" )
.appendTo( ul );
};
});
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log(ul, item)
return $("<li>")
.append("<b style=color:orange;>" + item.label + "</b>")
.appendTo(ul);
};
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
</body>
I have this live search and it works perfectly. What i want to do is I want to get another field. Aside of fetching indcator name i also want to get its ID by assigning it to another input type once I clicked the indicatorname using live search.
Heres the Script :
<script type="text/javascript">
$(document).ready(function() {
$('#indicatorname').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'indicatorname'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
selectFirst: true,
minLength: 0,
focus : function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
select: function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top");
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
$('#slider').rhinoslider({
effect: 'transfer'
});
});
</script>
Heres the ajax.php :
<?php
$connection = pg_connect("host=localhost dbname=brgy_profiler
user=postgres password=password");
if (!$connection)
{
echo "Couldn't make a connection!";
}
?>
<?php
if($_GET['type'] == 'indicatorname'){
$result = pg_query("SELECT cindicatordesc,nindicatorid from
tbl_indicators where cindicatordesc LIKE
'%".$_GET['name_startsWith']."%'");
$data = array();
while ($row = pg_fetch_array($result))
{
array_push($data, $row['cindicatordesc']);
}
echo json_encode($data);
}
?>
Here's my tbl_indicator :
How can i get also the nindicatorid field and get it together with cindicatordesc using ajax live search?
Note: Only cindicatordesc will be displayed and nindicatorid will be save in an input type.
Not a problem. You can add additional data attributes in your Auto-complete select return as,
$('#indicatorname').autocomplete({
source: function( request, response ) {
...........
success: function( data ) {
response( $.map( data, function( itemList ) {
return {
label: itemList.label,
value: itemList.value,
extraField : itemList.extraField
}
}));
So, Only change you need to accommodate is the Server side where you need to send the extra values to the Auto-complete AJAX.
And , On select event you can fetch the value as ui.item.extraField.
Here is a Sample Demo of using multiple attributes. Although it is not same as you have done, the inner logic is the same.
I am trying to validate part of a form, I am stuck on checking the database to see if a company name exists before submitting the form. This is a stripped down demo from the jquery ui modal from with the addition of checking if the company already exists. I am aware of SQL injection and am not doing anything about it just yet. At the moment the form won't submit as I'm missing something, I just don't know what yet.
Any help would be much appreciated.
This is what I have so far
The JS code:
$(function() {
var dialog, form,
company_name = $( "#company_name" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkCompany( o, n ) {
$.ajax({
type: "POST",
url: "crud.php?act=check",
data: "&company_name=" + o.val(),
success: function(response){
if(response > 0){
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
})
}
function addUser() {
var valid = true;
valid = valid && checkCompany( company_name, "Company Name already exists." );
if ( valid ) {
$.ajax({
type: "POST",
url: "crud.php?act=create",
data: "&company_name=" + company_name.val(),
success: function(data){
}
});
dialog.dialog( "close" );
}
return valid;
}
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 350,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});
$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
});
The php side (crud.php):
include 'connection.php';
$action = $_GET['act'];
if(isset($_POST['company_name'])){
$company_name = $_POST['company_name'];
}
switch($action){
case 'create':
$q = "INSERT INTO company_info (company_name) VALUES
('".$company_name."')";
mysql_query($q);
break;
case 'check':
$result = mysql_query('SELECT company_name FROM company_info WHERE company_name = "'.$company_name.'"');
$num = mysql_num_rows($result);
echo $num;
break;
}
CheckCompany returns nothing. You are returning true or false from success but that goes nowhere.
You need an outer deferred so you can return something from your ajax success, back through checkcompany out to your call.
Basically, checkcompany is called and exits/returns normally. SOme time later, the success function runs but that is independent because it's async. It's not part of your checkcompanmy function.
Ideally, you should trigger an event on ajax success that your element subscribes to.
Examples from comment below:
checkCompany(o,n) {
var retval = false;
$.ajax({
sync : true,
success: function(data) {
retval = true;
}
});
return retval;
}
OR asynch:
checkCompany(o,n) {
$.ajax({
success: function(data) {
$("#ID").trigger('ajsuccess.company');
}
});
}
OR using returned promise:
if (valid) {
checkCompany().done(function() {
do the secondary ajax call in here
}
}
checkCompany(o,n) {
return $.ajax();
}
I'm using this jquery plugin : JQuery Autocomplete. Problem I'm getting json data but it's not appearing on the autocomplete list.
The JQuery code:
$( "#student-id" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/ajax_admin.php?auto_student=" + $( "#student-id" ).val(),
dataType:"json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.students, function( item ) {
return {
label: item.id +" , "+ item.name,
value: item.id
}
}));
}
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The PHP Script is :
public function load_ajax_student_list($val)
{
$val = "%".$val."%";
$stmt = $this->conn->prepare("select * from student where studentAiubId like :value limit 0,5");
$stmt->bindValue(':value', $val);
$stmt->execute();
if($stmt->rowCount() < 1)
echo "";
else
{
$result = $stmt->fetchAll();
$output = array();
foreach($result as $row)
{
if($row['mname']=="")
$name = $row['fname']." ".$row['lname'];
else
$name = $row['fname']." ".$row['mname']." ".$row['lname'];
$data["name"] = $name;
$data["id"] = $row['studentAiubId'];
$output["students"][] = $data;
}
echo json_encode($output);
}
}
If the call goes like this: ajax/ajax_admin.php?auto_student=10
The produced data from PHP script is :
{
"students": [
{"name":"Moh Mamun Sardar","id":"10-15987-1"},
{"name":"Rehan Ahmed","id":"10-12451-2"},
{"name":"Abid Hassan","id":"10-15412-1"},
{"name":"Abir Islam","id":"10-11245-1"}
]
}
But Nothing showing on autocomplete. What I'm doing wrong?
try something like this
$.map( data.students, function(item ) {
return {
label: item.name,
value: item.id
});
it is minlength not minLength see casing
You have forgotten the "appendTo" property. In this propery you have to specify the selector of the element you wish the information to be appended to like this
appendTo: '.class' or appendTo: '#id'
You have to add this property to the initialization of the autocomplete as a sibling of source and etc ...
using jquery to post a value to php file but the value is not being posted (COMPANY_NAME). Code below works for multiple values but not when it's changed to post single values? Any tips?
$(function() {
$( "#dialog:ui-dialog" ).dialog( "destroy" );
var COMPANY_NAME = $( "#COMPANY_NAME" ),
allFields = $( [] ).add( COMPANY_NAME ),
tips = $( ".validateTips" );
$( "#dialog-form5" ).dialog({
autoOpen: false,
height: 200,
width: 350,
modal: true,
buttons: {
"ok": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
if ( bValid ) {
$.post("setCompany.php", {
COMPANY_NAME:$(this).val()
}, function(data) {
if(data=='no')
{ $("#msgbox").fadeTo(200,0.1,function()
{
$(this).html(data).addClass('messageboxerrorAdd').fadeTo(900,1);
});
} else if (data=='wrong') {
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html("fjdhffh").addClass('messageboxerrorAdd').fadeTo(900,1);
});
} else {
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html(data).addClass('messageboxerrorAdd').fadeTo(900,1);
});
}
});
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
});
Try this :
$.post("setCompany.php",{"COMPANY_NAME":COMPANY_NAME.val()}, function(data)...
JSON objects require keys to be surrounded by double quotes
COMPANY_NAME:$(this).val()
I don't think that $(this) points to the company name field. Try this:
"COMPANY_NAME" : COMPANY_NAME.val()
(as mentioned before, JSON keys need to be in double quotes)