When I fill search box, auto-completion doesn't work correctly. My query doesn't work.
Below is my html code:
$(document).ready(function(){
$('#keyword').autocomplete({
source: function( request, response ) {
$.ajax({
url : '/search',
dataType: "json",
data: {
username: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
id: '<B>' + item.id + '</B>',
value: item.value
}
}));
}
});
},
autoFocus: true,
minLength: 2,
select: function(event, ui) {
var url = ui.item.id;
if(url != '#') {
location.href = '/admin/users/' + url+ '/edit';
}
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
<input name="keyword" id="keyword" class="form-control txt-auto"/>
my function
public function search(Request $request) {
$keyword = $request->input('keyword');
$results = array();
$user = User::where('username', 'LIKE','%'.$keyword.'%')->get();
foreach ($user as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->username ];
}
return Response::json($results);
}
Route::get( '/search' , 'ShopController#search' );
I know i'm late to the party but I had this exact issue.
The z-index needs to be added while loading of your html:
What I did was I added this to one of my css files:
.ui-autocomplete {
z-index:2147483647;
}
After that, the autocomplete started working.
I haven't used autocomplete in a while, but I see two problems in your code. First, according to the docs
The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
Yet, you are using:
$keyword = $request->input('keyword');
instead of
$term = $request->input('term');
Second, maybe you need an ajax call inside the source option for something in particular, but you can simply do:
$('#keyword').autocomplete({
source: "/search",
select: function(event, ui) {
// ... do something here. Try logging the output
console.log(ui.item);
}
});
Related
Im adding enhancements to an existing rails 5.1 app. I need to add autocomplete with data retrieved from a Mysql database. The application has Jquery, simple_form, and materialize all included. My autocomplete is not working. It is not even getting to the controller. I have tried different examples found online and none work. I am hoping someone can help me.
HTML in HAML code snippet (only snippet)
= simple_form_for #vehicle, url: url_for(controller: 'trip_permits', action: 'update'), html: { method: :patch } do |v|
.input-field.col.s12.m4
=v.label :registration_number
= v.text_field :registration_number, input_html: { class: 'force-upcase' }
.cssbuttons.alternate
-# = link_to 'Cancel', '#', onclick: "$('.new_vehicle').hide();", class: 'btn btn-grey'
%button{ type: 'submit', class: 'btn btn-green', id: 'add'}
Add
Id of field is generated to trip_permits_vehicles_form_registration_number
JQUERY SNIPPET
`
$(document).ready(function () {
``
$("#trip_permit_vehicle_form_registration_number").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url:'/customers/trip_permits/autocomplete_vehicle_registration_number',
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});
}
});
I know I am missing something. Im not worried right now about the results because I cant even get the ajax call to work.
Can someone please help????
I have tried all the examples I could find online
Ive tried select2, simple_form_autocomplete, materialize-autocomplete
How about this?
$("#trip_permit_vehicle_form_registration_number").autocomplete({
search: function () {},
source: function(request, response) {
$.getJSON(
"/customers/trip_permits/autocomplete_vehicle_registration_number",
{term: request.term },
response
);
},
minLength: 2,
select: function (event, ui){
var test = ui.item ? ui.item.id : 0;
if (test > 0) { alert(test); }
}
})
I have a trouble with wordpress ajax call.
Action for admin-ajax.php has been defined correctly.
It returns correct result when user logged in, but it returns empty when user didn't log in.
Here is code for it.
add_action('wp_ajax_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
add_action('wp_ajax_nopriv_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
public function wp_ajax_action_calculate_extra_cost_handler() {
$return = array(
'code' => 'E001',
'message' => ''
);
echo json_encode($return);
exit;
}
And here is javascript code.
var data = {
action: "thwepo_calculate_extra_cost",
price_info: JSON.stringify(requestData)
};
currRequest = $.ajax({
type: "POST",
url: args.ajax_url,
data: data,
beforeSend: function() {
null != currRequest && currRequest.abort()
},
success: function(rslt) {
if ("E000" === rslt.code) {
var result = rslt.result;
result && display_new_price(args, result.display_price, isVariableProduct)
} else "E002" === rslt.code && display_new_price(args, rslt.result, isVariableProduct)
},
error: function(data) {
console.log(data);
}
});
Here is screenshot of ajax call.
It returns correct result when page loaded first time.
But when select option (i.e. Classes), it returns empty.
Why is this happened?
Is there anyone who have any idea?
Please let me know if needed any other information.
Page url is https://www.ivybound.net/classes/isee-prep-middle-level/
It can be checked by selecting "What do you need?" select option.
I am working on jquery autocomplete in mvc platform. Now, my question is that in some textbox data autocomplete is working properly while in some textbox data autocomplete is not working properly.
For more clear, lets see the image of autocomplete task
now as per the image when I write the R word, I am getting the suggestion list of related R word.
now as per the second image I have written the whole word but still suggestion is not display.
Here is my code,
View
<input type="text" id="CustomerName" name="CustomerName" required data-provide="typeahead" class="typeahead search-query form-control autocomplete"
placeholder="Customer Name" />
<script>
$(document).ready(function () {
$.ajax({
url: "/ServiceJob/CustomerSerchAutoComplete",
method: "GET",
dataType: "json",
minLength: 2,
multiple: true,
success: function (data) {
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
//autocomplete(document.getElementById("CustomerName"), data.data);
$('#CustomerName').autocomplete({ source: data.data, minLength: 2, multiple: true });
}
});
});
</script>
Controller
[HttpGet]
public IActionResult CustomerSerchAutoComplete()
{
var customers = _Db.Ledger.Where(x => x.LedgerTypeId == (int)LedgerType.Customer).ToList();
var result = (from n in customers
select new
{
kk = n.Name.ToUpper()
}).ToList();
return Json(new { data = result });
}
As you are getting
Uncaught TypeError: Cannot read property 'substr' of undefined
For this error you should check that data is not null.
success: function (data) {
if(data != null)
{
autocomplete(document.getElementById("CustomerName"), data.data);
}
}
I have a PrestaShop module called 'MyMenu' and I want call this menu with an AJAX call.
My module is displayed in the hookFooter() method:
public function hookFooter()
{
$display = $this->display(__FILE__, 'megamenu.tpl', $smartyCacheId);
Tools::restoreCacheSettings();
return $display;
}
I want display with this script:
<div class="load_menu"></div>
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "../modules/MyMenu.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
The best way is to do it via a front controller linked to your module.
You can call the url like this :
$link->getModuleLink('modulename','controller', $parameters);
// Parameters is an optionnal array, it can be empty
And for the controller, place a file like this ./modules/modulename/controllers/front/ajax.php with this kind of content :
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$response = array('status' => false);
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
$module = new ModuleName;
if (Tools::isSubmit('action')) {
$context = Context::getContext();
$cart = $context->cart;
switch (Tools::getValue('action')) {
case 'actionname':
$response = array('status' => true);
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
$this->ajaxDie($json);
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
If you don't want to pass the url by the module, the js snippet should be like this.
$(document).ready(function(){
$.ajax({
type: "POST",
headers: { "cache-control": "no-cache" },
url : baseDir + 'modules/yourmodulename/yourfile.php',
data: {
token : token
},
success : function(data){
$('.load-menu').html(data)
}
});
});
Where yourmodulename is the name of your module and yourfile.php is the code where you retrieve the menu.
Don't forget to add to your data the token, it's to prevent a CSFR attack, obviously you have to check the token in your server side script as well.
In a new file at the module root, you can create a file "ajax.php"
require_once(MODULE_DIR.'MyMenu/mymenu.php');
if(Tools::getValue('token') !=
$mymenu = Module::getInstanceByName('mymenu');
$menu = $mymenu->hookFooter();
die($menu);
In your js, at the root of your module
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "./ajax.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
I'm trying to use the newest version of Select2 to query my site's API and return a multiple-select. It's fetching the right data and it's even formatting the dropdown properly, combining two keys in the returned objects as "(A-123) John Johnson", but the dropdown's not responding to mouseover or clicks.
I'm using the select2.full.min.js and select2.min.css files. For the purposes of the project, I'm including them in the directory and accessing them through Bundles in cshtml, instead of accessing them via a CDN.
HTML:
<div>
<select class="user-list" multiple="multiple" style="width: 100%">
</select>
</div>
At the moment, it's looking like this, which is how I want it:
Not sure if this is relevant, but when I browse the generated source code while searching, the input looks fine, but the dropdown's code is greyed out as though it were hidden.
Per other suggestions I've found on here and elsewhere, I've tried a few different solutions. I eventually found out how templateResult and templateSelection are supposed to work (not particularly thanks to the documentation), and tried returning the ID as well, but I still can't seem to actually select anything, or even get a response when I hover over the options.
Here's what I wound up with, including some debugging to make sure the returned object is valid.
JS:
// Setup autocomplete/select for User filter
$(".user-list").select2({
ajax: {
url: "[api url]",
type: "GET",
dataType: "json",
data: function (params) {
return {
search: params.term, // search term
page: params.page
};
},
processResults: function (data) {
console.log(JSON.stringify(data));
return {
results: data
};
},
},
escapeMarkup: function (markup) { return markup; },
id: function (data) { return data.Id.toString(); },
minimumInputLength: 1,
templateResult: function (data, page) {
return "(" + data.User + ") " + data.Name;
},
templateSelection: function (data, page) {
return "(" + data.User + ") " + data.Name;
}
})
The ID is a GUID, and there are two other fields, which I'll call Name and User.
Data Sample:
[
{
"Id":"a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1",
"Name":"John Johnson",
"User":"A-123"
},
{
"Id":"b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2",
"Name":"Tom Thompson",
"User":"B-456"
}
]
I hate to add to the pile of questions that seem to be about this, but most results I've found have been for the older version with significantly different options, and they just haven't worked for me yet.
The way select2 operates is that it uses the "id" values of each data object and puts those into the original Select element as the selected option(s). This is case-sensitive.
By default, it displays the dropdown options and the selected element by whatever the "text" value is of the data object. This does not allow for custom formatting.
If (like me) you want to return different data options, you still need to return a field as "id", or re-map a field to "id" in an object returned in the processResults option under ajax. Then use the templateResult and templateSelection settings with your other returned data to display what you want.
If you return and parse everything correctly except for the id, you may wind up with an otherwise functional list, but be unable to select any options.
The requirements for the dropdown changed a bit with my project, but here's where I wound up. It works fine the multiple="multiple" attribute added to to make it a multi-select, too.
<select class="select2" style="width:100%; height: 100%;">
<option></option>
</select>
$(".select2").select2({
ajax: {
url: "[api url]",
method: "get",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
placeholder: "Enter a User ID or Name",
templateResult: function(data) {
return "(" + data.user + ") " + data.name;
},
templateSelection: function(data) {
return "(" + data.user + ") " + data.name;
}
}).ready(function () {
$(".select2-selection__placeholder").text("Enter a User ID or Name")
})
It's possible part of my initial issue was all the attempts at implementing fixes for older versions of Select2, which had a completely different set of options/settings available.
Additionally, a bit of a side-note, the "placeholder" attribute doesn't currently work with custom templating. It tries to force the placeholder text into the Result format, which shows "(undefined) undefined" with this code. To fix it requires an empty option and to replace the text on select2.ready.
I had the same problem. Solution:
added this part :
_.each(data.ResultObject, function (item) { item.id = item.K_CONTACT; });
(used underscore)
for my init
$(".js-data-example-ajax").select2({
ajax: {
url: "api/MyApi/MyApi",
method: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
SearchPart: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
_.each(data.ResultObject, function (item) { item.id = item.K_CONTACT; });
return {
results: data.ResultObject,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
multiple: true,
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
tags: true,
templateResult: self.Select2FormatData, // omitted for brevity, see the source of this page
templateSelection: self.Select2FormatDataSelection // omitted for brevity, see the source of this page
});