I am using jquery automcomplete with the Ajax call but what i want is if part is present in the json data fetched by the ajax on first call then i want to return that data as it is without giving the ajax call i have tried it as below
function SearchText() {
var cache = {};
$("#txtItem").autocomplete({
source: function (request, response) {
var term = request.term;
$.each(cache, function (index, value) {
$.each(value, function (index, value) {
if (value.indexOf(term) >= 0) {
response(cache[term]);
return;
}
});
});
cache = {};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{'item':'" + document.getElementById('txtItem').value + "'}",
dataType: "json",
success: function (data) {
cache[term] = data.d;
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
minLength: 3
});
}
but even if it finds the matching term in the array then also it generates the ajax call.
I m stuck here for 3 hrs now any help would be great. I have tried maxCacheLength but it is also not working.
Try this out, sometime ago i faced same problem and came up with this it might work for you
function SearchText() {
var cache = {};
var oldterm;
$("#txtItem").autocomplete({
source: function (request, response) {
if (request.term.indexOf(oldterm) >= 0) {
if (typeof (oldterm) != 'undefined') {
var data = jQuery.grep(cache[oldterm],
function (ele) {
return (ele.indexOf(request.term) >= 0);
});
response($.map(data, function (item) {
return { value: item }
}))
return;
}
} else {
cache = {};
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'item': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
oldterm = request.term;
cache[request.term] = data.d;
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (result) {
alert("Error");
}
});
}
},
minLength: 3,
select: function (event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Here is a solution i found for you, It uses jQuery UI's autocomplete using cache and $.map function
function SearchText() {
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Hope this helps.
Related
What is the best way to send a request to the Amadeus API with a form field that uses autocomplete in a Rails app?
I am adding autocomplete to a search form to query the Amadeus "Airport and City Search".
I am using Rails 6 and gem 'amadeus'.
I get a 401 Unauthorized error when I type 3 letters into the search form. How can I authorize my request and make this autocomplete work?
Here is my javascript:
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://test.api.amadeus.com/v1/reference-data/locations",
dataType: "json",
data: {
apikey: "my_api_key_here",
keyword: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 3,
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");
}
});
});
Here is an authorized request with javascript using the gon gem to get the access token in javascript.
$(function() {
amadeus_client = gon.amadeus
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
console.log("Requesting Token...");
var settings = {
"url": "https://test.api.amadeus.com/v1/security/oauth2/token",
"method": "POST",
"timeout": 0,
"data": {
"client_id": amadeus_client.client_id,
"client_secret": amadeus_client.client_secret,
"grant_type": "client_credentials"
}
};
$.ajax(settings).done(function (response) {
console.log("Assigning Token variables...");
ACCESS_TOKEN = response.access_token;
console.log("Access Token : " + ACCESS_TOKEN);
});
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
type: "get",
url: "https://test.api.amadeus.com/v1/reference-data/locations",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization',
'Bearer ' + ACCESS_TOKEN);
},
data: {
keyword: request.term,
subType: "CITY"
},
success: function(data){
// console.log(data);
response($.map(data.data, function(el){
return {
label: el.detailedName,
value: el.iataCode
}
}));
}
});
},
minLength: 3,
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");
}
});
});
I am following this tutorial:
https://gist.github.com/ChinhP/9b4dc1df1b12637b99a420aa268ae32b
I have a problem where the ajax won't fire. Any suggestions?
I am trying to get a table with a previous, next, first and last button.
var data = { "number": 0, "currentPosition": 1 };
console.log(JSON.stringify(data));
//var output = "";
/*$.ajax('/Companies/GetData', {
datatype: 'json',
contentType: 'application/json',
type: 'post',
data: JSON.stringify({ dataTableParameters: data }),
success: function (response) {
output = response;
}
});*/
$(document).ready(function () {
$('#CompanyTable').dataTable(
{
"sPaginationType": "full",
processing: true,
bserverSide: true,
ajax: {
"url": "../Companies/GetData",
"type": "POST",
"contentType": "application/json",
data: function (d) {
console.log('enter');
// note: d is created by datatable, the structure of d is
the same with DataTableParameters model above
console.log(JSON.stringify(d));
return JSON.stringify(d);
},
success: function (response)
{
console.log(response)
}
}
});
});
I've been dealing with Couchbase-Lite-PhoneGap-Plugin.
I've try to create a design document in an Android emulator using REST API. But every time I get status: 400 - Bad request message and I cannot find my mistakes.
My codes are the following;
var cblUrl = "";
var dbName = "user";
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
if(window.cblite) {
window.cblite.getURL(function(err, url) {
if(err) {
console.log("error launching Couchbase Lite: " + err);
} else {
console.log("Couchbase Lite running at " + url);
cblUrl = url;
}
});
} else {
console.log("error, Couchbase Lite plugin not found.");
}
// jQuery Main function
$(function() {
$("#connect").on("tap", function() {
$.ajax({
url: cblUrl + '_all_dbs',
type: 'GET',
success: function (data, textStatus, xhr) {
if (data.indexOf(dbName) == -1) { // db doesn't exist
// create a database (bucket)
$.ajax({
url: cblUrl + dbName,
type: 'PUT',
async: true,
success: function (data, textStatus, xhr) {
console.log(xhr.status);
},
error: function (xhr, statusText, errorThrown) {
console.log(xhr.status);
}
});
} else {
console.log("db exists");
}
},
error: function (xhr, statusText, error) {
console.log(xhr.status);
}
});
}); // #connect tap
// create button tap event
$("#create").on("tap", function() {
var view = {
"language" : "javascript",
"views" : {
"view_user" : {
"map" : "function(doc) {if (doc.username) {emit(doc.username, null)}}"
}
}
}
// ** create VIEW **
$.ajax({
url: cblUrl + dbName + "/_design/users",
type: 'PUT',
data: view,
success: function (data, textStatus, xhr) {
console.log(xhr.status);
},
error: function (xhr, statusText, error) {
console.log(xhr.status);
}
});
});
}); // main jQuery function
}, // onDeviceReady
};
app.initialize();
I had installed my plugin using command of
cordova plugin add com.couchbase.lite.phonegap
However the plugin was beta and a former version at plugins.cordova.io.
And then I've tried to uninstall and re-install plugin using command of
cordova plugin add https://github.com/couchbaselabs/Couchbase-Lite-PhoneGap-Plugin.git
I was able through this way.
I am displaying data from the user on the user page and i would like to notify the user once all the data has been loaded and there is no more data to retrieve from the server using knockout.
Knockout script
$.views.Roster.GetPage = function ( pageNumber) {
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
}
});
};
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1)
};
$.views.Roster.BindModel = function (data) {
var self = $.views.Roster.ViewModel;
$.views.Roster.ViewModel.TotalRoster = ko.computed(function () {
return self.RosterUsers().length;
});
$.views.Roster.RosterViewModel.AddUsers(data);
ko.applyBindings($.views.Roster.ViewModel);
}
Next = function () {
var _page = $.views.Roster.ViewModel.CurrentPage() + 1;
$.views.Roster.ViewModel.CurrentPage(_page);
$.views.Roster.GetPage(_page);
};
$.views.Roster.RosterViewModel = function (data) {
$.views.Roster.RosterViewModel.AddUsers(data);
};
$.views.Roster.RosterViewModel.AddUsers = function (data) {
$.each(data, function (index, value) {
$.views.Roster.RosterViewModel.PushUser(value);
});
};
$.views.Roster.RosterViewModel.PushUser = function (user) {
$.views.Roster.ViewModel.RosterUsers.push(new $.views.Roster.UserViewModel(user));
};
When you say 'once all the data has been loaded', I assume you mean when the GetPage method finishes loading a single page of users, as that is the only data loading that I see in the code above. Here is one way you can do it:
First, create an observable somewhere that you can bind to to tell the user if data is loading
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1),
DataIsLoading: ko.observable(false)
};
And add some markup that shows something in the UI when data is loading
<div data-bind="visible:DataIsLoading">Data is Loading, please wait...</div>
Then set DataIsLoading before you make the ajax call, then reset it when the call is done
$.views.Roster.GetPage = function ( pageNumber) {
$.views.Roster.ViewModel.DataIsLoading(true); // Add this!
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
}
});
};
I have a 2 dropdownlist, I have to bind the 2nd one based on the Id I got from first dropdown. in the first dropdown I added OnChange event.
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type: 'post',
data: { productId: $("#ProductName").data("tDropDownList").value() },
success: function (data) {
$.each(variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">' + variant.Name + '</option>');
});
},
error: function () {
alert('Error');
}
});
}
and this is the c# code .
[HttpPost]
public ActionResult GetProductVarinats(string productId)
{
var variants = _productService.GetProductVariantsByProductId(Convert.ToInt32(productId));
return Json(new { Result = true, data = variants }, JsonRequestBehavior.AllowGet);
}
but it does not work.
Use val() instead of value()
Change statement
data: { productId: $("#ProductName").data("tDropDownList").value() }
to
data: { productId: $("#ProductName").data("tDropDownList").val() }
and the success should be like
success: function (data) {
//For getting list of variants, you should access it by `data.data.variants`
//because you will get your json object in data, and for getting the value `variants`
//you should capture the `data` property of returned json object like `data.data`
$.each(data.data.variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">'+ variant.Name + '</option>');
//you can try this also for creating options
//$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
}
so your function should look like :
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type : 'post',
data: { productId: $("#ProductName").data("tDropDownList").val() },
success: function (data) {
$.each(data.data.variants, function (i, variant) {
$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
},
error: function () {
alert('Error');
}
});
}
AcidMedia has a library called TTControls which uses Telerik and you can use the TTControls.LinkedDropDown control which solves this problem.