I have following codes to implement an autocomplete for a form field
$( "#manager" ).change(function() {
var rows;
var manager = $(this).val();
var grouplist = $.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager);
$( "#groups" ).autocomplete({ source: grouplist });
});
This is post response.
[{"personnel_name":"nab_group_1_1"},{"personnel_name":"nab_group_1_2"},{"personnel_name":"nab_group_2_1"}]
obiviously its getting required values and is working.
But autoocmplete is not displaying any values.
I have put an alert on grouplist and it display object object.
Can someone please suggest me how i can fix this and whats wrong here.
Thanks in advance.
Check what autocomplete consumes. I think your object is being cast as a string hence Object Object. If you are passing JSON to autocomplete then ensure your backend gives JSON as a response.
try something like this
$.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager,function(response){
var grouplist = jQuery.parseJSON(response);
$( "#groups" ).autocomplete({ source: grouplist });
});
your autcomplete should be like this
EDITED CODE
$.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager,function(response){
var grouplist = jQuery.parseJSON(response);
var new_data_source = $.map( grouplist, function( item ) {
return {
label: item.nab_group_1_1,
value: item.personnel_name
}
});
$( "#groups" ).autocomplete({ source: new_data_source });
});
json should be like [{"id":"your_id","label":"your_label"}]
while your json is different so you have to create json on success
Related
I got a simple POST call to a PHP file on my website. For some reason it's not working though. The console.log shows"undefined"
function check() {
var url = "../API/keychecker.php";
var spullen = $("keyval").val;
$.ajax({
type: "POST",
url: url,
data: {
key: spullen
},
success: function(data) {
console.log(data);
}
})
}
Here is the PHP file:
<?php
echo json_encode($_POST['key']);
?>
Your keyval call doesn't specify the type of element identifier. jQuery won't find the element you're looking for as you currently have it.
You must specify:
For classes:
$( ".keyval" ).val();
For ID
$( "#keyval" ).val();
For input name
$( "input[name=keyval]" ).val();
That should attach the value to the POST request.
var url = "API/keychecker.php";
var spullen = $( "keyval" ).val();
im new to jquery ui autocomplete. Im basically using autocomplete with ajax, with PHP to get list of users.
autocompleteajax.js
$(function() {
$( "#ranksearch" ).autocomplete({
source: function( request, response ) {
console.log('in');
$.ajax({
url: "autocompleteajax.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
console.log(request);
console.log(data);
response(data);
}
});
},
});
});
and the JSON, that php is returning looks like this
{3: "Tomek To", 4: "Tomek Kula"}
The number is userid, and the string is Firstname Lastname. I would like to store the selected userid somewhere, after someone chooses it from autocomplete list. Is there any simple way to achieve it?
Thanks to help #Dev.Joel i found out the solution.
In php i stored users like this
$users[] = array('value'=>$uid,'label'=>$uname);
Then the i got the values in js by doing this
$(document).ready(function () {
$('#ranksearch').on('autocompleteselect', function (e, ui) {
e.preventDefault(); // prevent the "value" being written back after we've done our own changes
this.label = ui.item.label;
$('#ranksearch').val(this.label);
console.log(ui.item.value);
});
});
Something was broken meanwhile i did this and i had to assign myself the label to input, since it was using value.
I am adding an autocomplete library into my project using the jquery-ui library.
I created the PHP script from which I need to get the data:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
$cid = $_SESSION['clinic_id'];
$searchTxt = '%'.$_POST['searchTxt'].'%';
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid and patient_name_en LIKE :searchTxt ORDER BY patient_id DESC";
$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->bindValue(':searchTxt', $searchTxt);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();
$i = 0;
foreach($getPatientsResult as $result)
{
$res[$i] = $result;
$i++;
}
echo json_encode($res);
?>
And the JavaScript part is here:
<script>
$( function() {
$("#searchTxt").on('keyup', function(){
searchTxt = $("#searchTxt").val();
$.ajax({
url: '../php/autoComplete.php',
data: {searchTxt: searchTxt},
type: 'POST',
dataType: 'JSON',
success:function(resp)
{
$.each( resp, function(key, result)
{
var availableTags = result['patient_name_en'];
});
},
error:function(resp)
{
console.log(resp)
}
})
} );
$( "#searchTxt" ).autocomplete({
source: availableTags
});
});
</script>
I had the following error in the console about jQuery:
Maximum call stack size exceeded.
But now it gone somehow, and I don't know why.
Now after typing in the search text box, I am getting an empty array at the network tab of the developer tool or an array but with no properties and nothing is show as autocomplete near the text box:
EDIT
I changed a line in PHP into:
$searchTxt = '%'.$_POST['searchTxt'].'%';
And now no php errors, but a JavaScript error:
Uncaught ReferenceError: availableTags is not defined
$( "#searchTxt" ).autocomplete({
source: availableTags
});
success:function(resp)
{
$.each( resp, function(key, result)
{
var availableTags = result['patient_name_en'];
});
},
You have declared the availableTags inside the success method of ajax call and you are trying to access it outside it's scope.
Either you make availableTags as global variable or declare somewhere on the top so that you can access it in both the places ( for reassigning after ajax success and in the autocomplete method).
$( "#searchTxt" ).autocomplete({
source: availableTags
});
});
this code gets executed before your post gets success, it's non-blocking, so you have to write it something like.
$( function() {
$("#searchTxt").on('keyup', function(){
searchTxt = $("#searchTxt").val();
$.ajax({
url: '../php/autoComplete.php',
data: {searchTxt: searchTxt},
type: 'POST',
dataType: 'JSON',
success:function(resp)
{
$.each( resp, function(key, result)
{
var availableTags = result['patient_name_en'];
$( "#searchTxt" ).autocomplete({
source: availableTags
});
});
});
},
error:function(resp)
{
console.log(resp)
}
})
} );
});
I'm trying to access and display a variable within a json object on my page. Can anyone tell me why the variable gets displayed three times?
my_array.php
<?php
$my_data=array(name=>"john",age=>"30", city=>"copenhagen");
// sending output
header('Content-Type: text/json');
echo json_encode($my_data,true);
?>
My_page.php
<script>
$(document).ready(function() {
$("button").click(function() {
$.getJSON("my_array.php", function(data) {
$.each(data, function(key) {
$("#showdata").append(data.city);
});
});
});
});
</script>
//Show the data further down the page.
<div id="showdata"></div>
This displays
copenhagencopenhagencopenhagen
That's because you're iterating over 'each' data item from the json response that you receive and there are 3 key=>value pairs in my_array.php
Removing "$.each(data, function(key) {} " will return the value 'city' only once
$(document).ready(function(){
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
});
use this
my_array.php
<?php
$my_data = array(
name => "john",
age => "30",
city => "copenhagen"
);
// sending output
header('Content-Type: application/json');
echo json_encode($my_data, true);
?>
My_page.php
<div id="showdata"></div>
<button>Click Me!</button>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(e){
$.getJSON("test.php", function(data){
console.log(data);
$("#showdata").append(data.city);
});
});
});
</script>
this will give you only one copenhagen.
hope it helps...
First things first:
Set either:
header("Content-Type: application/json");
Above:
echo json_encode($my_data,true);
On your php file.
Or use the following snippet on your javascript:
$.getJSON("my_array.php",function(data)
{
data=JSON.stringify(data);
$.each(data, function(key)
{
$("#showdata").append(data.city);
});
});
Furthermore either in both ways above the returned data is an Object so in order to return correctly on your php file the data must be:
$my_data=array(array(name=>"john",age=>"30", city=>"copenhagen"));
Note: Associative arrays on php's json_encode turned into Objects. Non associative arrays on json_encode still remain an array
Im guessing because you have got three buttons on the page and the $.each takes the selector try:
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
you're iterating 3 times because of the three keys you have within the JSON object,
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log( "key + " " + val" );
});
take a look at the JQuery documentation for further info.
http://api.jquery.com/jquery.getjson/
I've been trying to amend the example from http://jqueryui.com/autocomplete/#maxheight to work with input from a locally stored text/csv file looking like
ItemA
ItemB
ItemC
....
I am able to create an array from the data in the textfile and print it to console.log() but I'm not sure how to hand over this array to the autocomplete function. I've tried initializing the array a outside the function but when using it in autocomplete it will use the non-populated array a.
</style>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "john.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
}
$( "#tags" ).autocomplete({
source: a
});
</script>
How do I pass the array correctly to autocomplete?
I think you are trying to add autocomplete source before the AJAX query is completed.
The query is done on $(document).ready() but the autocomplete source is set before it. So a still remains empty.
Try this:
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
$( "#tags" ).autocomplete({
source: a
});
}