Autocomplete issue: Content is not displaying - php

Content is not displaying is autocomplate list as you can see in screenshot below.
I am getting this response.
[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"},{"emp_number":4,"fname":"test","lname":""} .......... REMOVED TO MAKE IT LOOK BETTER HERE .......]
My JS Code:
$( "#search-emp" ).autocomplete(
{
source: function (request, response)
{
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'
};
$.ajax({
//contentType: "application/json",
type: "POST",
dataType: 'json',
url: "_ajax.php",
data: form_data,
success: function( data )
{
response( data );
}
});
},
minLength:3,
select:function(evt, ui)
{
alert(ui.item.emp_number);
}
});
I want to display fname and lname on selected into input field.

The problem it's because jQuery autocomplete wants to have 2 fields named label and value. The content from label will be displayed in the autocomplete.
Because your server return other name for the keys you have 2 options:
Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]
Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source

Related

jQuery Select2 JSON data

My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

Typeahead: Match ajax result with multiple attributes

I am using Bootstrap Typeahead (version: v2.0.0). I have result set through an ajax call and would like to show autocomplete list using value and one more attribute.
I have result set like:
{"res":[{"id":617,"value":"DESC: Admin responder comment","user_id":37,"status":1,"comment":"Hi {firstname},\n\nThis is testing.","firstname":"Tom's"},
{"id":625,"value":"DESC: my comment","user_id":37,"status":1,"comment":"Hi {first_name}, anther testing comment","firstname":"William's"}
]}
Autocomplete matching keyword with value attribute and populating it. But, I would like to match keyword with comment attribute as well.
I have tried matcher of typeahead and some solutions mentioned on SO as well but did not found useful. Tried one here: but getting error of "TypeError: Bloodhound is undefined" with that solution.
Please check code below used for autocomplete using result by ajax.
var typeahead_pre_written_xhr = null;
var search_keyword = function ( tid, txtElmt )
{
$( "#typeahead-input" ).typeahead({
items: 20,
source: function(typeahead, query) {
action_url = _base_url + "search/search_keyword/";
typeahead_pre_written_xhr = $.ajax({
cache: false,
type: "POST",
dataType: "json",
url: action_url + query,
data: { 'type': type },
error: function (request, status, error) { },
success: function(data) {
if( typeof data.res != 'undefined' && data.res != '' ) {
typeahead.process(data.res);
}
}
});
},
onselect: function() {
// Do stuff
}
});
};
Please help me to achieve this.

Select2 with AJAX always no result found

Following tutorial Select2 with AJAX, I am trying retrieve students list with ajax. my input is :
<select class="form-control" id="student_id" name="student_id"></select>
and the script is :
var url = '';
url += "{{ route('api.student_list') }}";
console.log(url); //outputs http://localhost/project-child/public/api/get-students
$( "#student_id" ).select2({
placeholder: 'Select an item',
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
The JSON response is similar to
[{"id":1,"text":"EJAJUL HAQUE"},{"id":2,"text":"MUSTAK AHMED"},{"id":3,"text":"AZAD HOQUE"},{"id":4,"text":"ANJARUL HAQUE"},{"id":5,"text":"ARIFUL ISLAM"},{"id":6,"text":"SANJITA KHATUN"},{"id":7,"text":"MARINA SULTANA"},{"id":8,"text":"SULTANA BEGUM"},{"id":9,"text":"SABINA KHATUN"},{"id":10,"text":"JENIFA AHMED"},{"id":11,"text":"REJUON AHMED"},{"id":12,"text":"FARITA KHATUN"},{"id":13,"text":"HABIJUL HOQUE"},{"id":14,"text":"JENIFA MUSKAN"},{"id":15,"text":"JOTUFA WAHID"},{"id":16,"text":"MAUSUMI BEGUM"},{"id":17,"text":"ABJARUL RAHMAN"},{"id":18,"text":"JANNATUR ANJU"},{"id":19,"text":"RIYAD "},{"id":20,"text":"RAJIBUL HOQUE"},{"id":21,"text":"UMME SALMA"},{"id":22,"text":"RAFIKUL ISLAM"},{"id":23,"text":"ABJAL HUSSAIN"},{"id":24,"text":"IMAM AHMED"},{"id":25,"text":"NARGIS SULTANA"},{"id":26,"text":"MAFUDA KHATUN"},{"id":27,"text":"SIDDIKUL NAHAR"},{"id":28,"text":"KHALEDA BEGUM"}]
But If I search , say EJAJ it says No results found. I am using select version 4.0.3
on processResults , count data and if its length == 0 then do smt ...
processResults: function (data) {
if(data.length==0){
getFromGoogle();
}
return {
results: data
};
},
Get rid of the whole processResults stuff and make your data server turn your JSON array a subarray with key results. This way:
{"results":[your-JSON-array-above]}

How to Select Data from database using Ajax and Plugin Select2

Please help me to solve my problem.
$("#kategori_laporan").change(function() {
$("#loaderIcon").show();
$("#imgLoader").show();
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "html",
url: "_views/getAjaxSubKategori.php",
data: "id="+id,
success: function(data) {
$(".select-skategori").select2({
ajax: {
url: "_views/getAjaxSubKategori.php",
dataType: 'json',
data: function(term, page) {
search = term.toUpperCase();
},
results: function(datas, page) {
return {
results: data
};
}
},
formatResult: function(option) {
return "<div>" +option._sub_kategori_laporan+ "</div>";
},
formatSelection: function(option) {
return option._sub_kategori_laporan;
}
});
}
});
});
Data not showing to subcategory select. Thanks before.!
Screenshot >> http://i.imgur.com/FlCeGpo.jpg
Why are you firing an ajax request before you initialize the select2 box?
I ask this, because your select2 box is requesting the search results via ajax as well. But maybe there is a reason. Please explain.
Then I can see in your screenshot, that your data returned from the json ajax request has not defined values id and text. If you are using other values ('_sub_kategori_id' and '_sub_kategori_laporan') in your json result, you have to tell the select2 box, what is your id and text field. I think you can do this with the processResults method as described here:
How to load JSON data to use it with select2 plugin

Jquery autocomplete in codeigniter retrieving values but not displaying them

After a few hours of deciphering tutorials, I finally got codeigniter and jquery autocomplete to work with each other...kind of.
Firebug is displaying the correct search terms back in JSON format, but the drop down box is not displaying any text. If there are 2 results, it displays 2 empty rows.
you can see it 'not working' here: http://rickymason.net/blurb/main/home
JS:
$(document).ready(function() {
$(function(){
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Controller:
public function search()
{
$term = $this->input->post('term', TRUE);
$this->thread_model->autocomplete($term);
}
Model:
public function autocomplete($term)
{
$query = $this->db->query("SELECT tag
FROM filter_thread ft
INNER JOIN filter f
ON ft.filter_id = f.filter_id
WHERE f.tag LIKE '%".$term."%'
GROUP BY tag");
echo json_encode($query->result_array());
}
Hopefully its an easy fix!
Thanks
Changing your code to something like this would work(I have tested in your site)
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
Copy and paste the above code block in your firebug console and then try the autocomplete. It will work. I tried in your site and it worked.
Secondly you dont need both $(document).ready(function() { and $(function(){ at the same time as they accomplish the same thing.
Check this section of jQuery UI autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with
label and value properties: [ { label: "Choice1", value: "value1" },
... ]
Reference: $.map
Looking at this question on SO you need to setup your label and value fields on the response return. Try either arranging your PHP JSON output to match or map the return with something this the following (untested).
response( $.map(data, function(item){
return {
label: item.tag,
value: item.tag
};
})

Categories