Jquery Autocomplete with Ajax Call not working - ajax

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); }
}
})

Related

How to use JSON result from autocomplete as variable for another autocomplete

I would like to ask You for help mi to figure it out, how to use result of first Complete which is giving me a client number as #select_client_id in another autocomplete.
At one page, i'm selecting order from autocomplete list:
$( function() {
$( "#select_order" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_order_out: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#select_order').val(ui.item.label); // display the selected text
$('#select_order_id').val(ui.item.value); // save selected id to input
$('#select_client_id').val(ui.item.client_id);
return false;
}
});
});
Then there is another input field which is selecting packages for this order, where i`m using a client id, from first autocomplete:
$("#select_package").autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_client_package_on_storage: request.term, client: client
},
success: function( data ) {
response( data );
console.log(client);
}
});
},
select: function (event, ui) {
$('.select_package').val(ui.item.label);
$('.select_package_id').val(ui.item.value);
return false;
}
});
For now, i've got only one client, so variable is declared by:
<script>
client="1";
</script>
How can i do it properly? :)
Well, it takes a little bit longer than normally, but it wasn't priory to figure it out :)
Answer is very simple :)
In #select_order autocomplete, i've add:
select: function (event, ui) {
$('#select_order').val(ui.item.label);
$('#select_order_id').val(ui.item.value);
$('#select_client_id').val(ui.item.client_id);
client_number=$("#select_client_id").val();
return false;
And at the end of body set a variable declaration:
<script>
let client_number = 0;
</script>
That solved my problem :)

how I can retrieve json in vuejs

How can I retrieve json in Vuejs in vue.js in laravel 4?
I tried following but it didn't work:
new Vue({
el: '#guestbook',
data: {
comments: [],
text: '',
author: ''
},
ready: function() {
this.getMessages();
},
methods: {
getMessages: function() {
$.ajax({
context: this,
url: "/cms/Getweb_manager",
success: function (result) {
this.$set("comments", result)
}
})
}
}
})
Have you tried logging the response? Just use a console.log(result).
About your doubt, you probably have to do this.$set('comments', result.data');.
Don't forget the semicolon!
Have a look at the vue-resource package
https://github.com/vuejs/vue-resource
It should work like this
methods: {
getMessages: function() {
this.$http({
url: '/cms/Getweb_manager',
method: 'GET'
}).then(function (response) {
// success callback
this.$set('comments', response.result);
}, function (response) {
// error callback
});
}
}

autocomplete search with jquery-ui - doesn't work

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);
}
});

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Use Ajax and JsonResult in ASP.NET MVC 3

I need to get string array or list with ajax and Action, this is my Implementation:
This is my html Dom of view of Index action in AccessMenuController:
<div class="RoleAccess">
<select name="RoleDropDown">
<option value="0">Select Role</option>
<option value="61AD3FD9-C080-4BB1-8012-2A25309B0AAF">AdminRole</option>
<option value="8A330699-57E1-4FDB-8C8E-99FFDE299AC5">Role2</option>
<option value="004E39C2-4FFC-4353-A06E-30AC887619EF">Role3</option>
</select>
</div>
My Controller:
namespace MyProject.Areas.GlobalAccess.Controllers {
public class AccessMenuController : Controller {
public ActionResult Index() { return View();}
[HttpPost]
public JsonResult RoleDropDownChanged(string roleId) {
Guid RoleId = new Guid(roleId);
//Some implement
List<string> actions = new List<string>();
for(int i = 0; i <= 10; i++)
actions.Add(i.ToString());
return Json(actions.ToArray(), JsonRequestBehavior.AllowGet);
}
}
}
and the script:
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler();
});
function RoleChangeHandler() {
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
function SuccessRoleChangeHandler(data) {
alert("in success role change");
}
function OnFailRoleChangeHandler(result) {
alert('in OnFailRoleChangeHandler');
}
And the problem is with all change of dropdown just Onfail function run and alert me "in OnFailRoleChangeHandler", also I check the RoleDropDownChanged Action with breakpoint and that never run, where is the problem?
UPDATE
when I load the page by chrome there is an error in console window:
http://MyProject/GlobalAccess/AccessMenu/#Url.Action(%22RoleDropDownChanged%22) 404 (Not Found) jquery-1.7.1.js:8102
Remove this setting:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server.
If you want to keep this setting then make sure that you are sending a valid JSON to your server:
data: JSON.stringify({ 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' })
So:
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: SuccessRoleChangeHandler,
error: OnFailRoleChangeHandler
});
should work (at least it does for me) with the following action:
[HttpPost]
public ActionResult RoleDropDownChanged(Guid roleId)
{
var actions = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList();
return Json(actions);
}
UPDATE:
According to your comments it looks like you are trying to use server side helpers in a separate javascript which is not possible. Here's what I would suggest you. Start by providing the url when generating your dropdown:
<div class="RoleAccess">
#Html.DropDownListFor(
x => x.RoleDropDown,
Model.Roles,
"-- Select role --",
new {
data_url = Url.Action("RoleDropDownChanged")
}
)
</div>
and then in your separate javascript file:
$(document).ready(function() {
$('div.RoleAccess select').change(function () {
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: function(result) {
alert('success');
},
error: function() {
alert('error');
}
});
});
});
and then of course you could replace the hardcoded roleId with the currently selected value:
data: { 'roleId': $(this).val() }
Move your $(document).ready function to your View like this:
<script type="text/javascript">
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler('#Url.Action("RoleDropDownChanged")');
});
});
</script>
Then in your JS file add url parameter to your function and change ajax call:
function RoleChangeHandler(pageUrl) {
$.ajax({
url: pageUrl,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
This should work as you expected.
If your script resides in a .JS file then this is not going to work as it'll be treated as plain text. You can either move entire script to the view or you can re-factor script so that majority of the script remains in the .JS and you then pass relevant values from the view.

Resources