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");
}
});
});
Related
How do I shape the payload to enable a post or patch for fields that are Hyperlink/Picture?
Getting those fields is straight forward: they come as "fieldName" : { "Description":"asdf", "Url":"asdf.com"}
This works in flow using the Send HTTP Request to SharePoint block, but I can't figure out how to make this work using the graph api. Do i need to set the odata type explicitly (SP.FieldUrlValue doesn't work) and what is it for Hyperlinks?
Somethink like this: {"fieldName#odata.type", "Complex" } - we use this with Collection(Edm.String) for multiple lookup fields for instance.
Kind regards,
Gregor
Graph API does not support create this kind of column.
https://learn.microsoft.com/en-us/graph/api/resources/columndefinition?view=graph-rest-1.0
You could try to use rest api.
Create HyperLink field:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
Update Hyperlink column:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google1',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(41)",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
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 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.
I am using jqxgrid and I have below code snippet and i want to display load indicator on button click which calls the Ajax method and hide it on the success method or anyway other to display it as i need to show loading indicator from the time request made till i get the data
$("#btnSearch").bind('click', function () {
//show indicator here
LoadLookUpSearchGrid();
}
//Ajax call to fetch data
function LoadLookUpSearchGrid() {
var filterRows = getGridRows();
$.ajax({
type: 'POST',
dataType: 'json',
async: false,
cache: false,
url: 'AddEditView.aspx/LoadLookUpSearchGrid',
data: JSON.stringify({ FilterType: $('select#ddlFilterType').val() , Id: $("#txtId").val() , Name: $("#txtName").val(), SearchText: '', FilterRows: filterGridRows}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
error: function (err) {
alert(err.text + " : " + err.status);
}
});
};
//source object to format data
function SetSearchFields(fieldName, source) {
var columns;
if (fieldName == "Operating Company") {
source =
{
datatype: "xml",
datafields: [
{ name: 'COMPANY', type: 'string' },
{ name: 'DESCR', type: 'string' }
],
async: false,
root: "Company",
localdata: source
};
columns = [
{ text: 'OPCO ID', dataField: 'COMPANY', width: '30%' },
{ text: 'Company Name', dataField: 'DESCR', width: '65%' }
];
}
lookupSearchResultGrid(source, columns,fieldName);
}
//adaptor to fill source and bind grid
function lookupSearchResultGrid(source, columns,fieldName) {
var searchViewGridDataAdapter = new $.jqx.dataAdapter(source);
$("#divLookupSearch").jqxGrid(
{
width: '100%',
source: searchViewGridDataAdapter,
theme: theme,
sortable: true,
pageable: true,
autoheight: true,
selectionmode: 'checkbox',
columns: columns
});
//hide indicator here on on success method of ajax call
};
On the click of the button call showloadelement and in the Ajax call success callback function call hideloadelement.
$("#btnSearch").bind('click', function () {
$('#divLookupSearch').jqxGrid('showloadelement');
//show indicator here
LoadLookUpSearchGrid();
}
...
success: function (data) {
$('#jqxGrid').jqxGrid('hideloadelement');
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
...
Best Regards,
Alpesh
This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.