jQuery autocomplete multiple fields - javascript

I have the below AJAX response which is an object containing a food item and price.
{
"pizza": "100.00",
"Burger": "45.00",
"Ice Cream": "25.00",
"Chips": "20.00",
"Peanut Butter": "50.00"
}
I'm trying to build a form wherein the user enters an item and the 'price' input field gets automatically filled. I went through the jQuery documentation and I'm confused as to how I can get the Item inputbox to only look for the 'food' items (or keys) in the array.
I'm getting a this.source is not a function in my console. I'm aware of the reason where I'm going wrong (I believe its due to the fact that they keys are different food items as opposed to 'label').
Here is my js
$(document).ready(function(){
var myItems = getData();
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
//below doesn't work in loop
// myItems['Item'] = json[i].Item;
// myItems['Price'] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log('Is this working '+ myItems);
console.log(myItems);
return myItems;
};
Please let me know how I can solve this issue.

The source option when you create the autocomplete needs to be either an Array of strings with the values, a String for a url with a JSON response that holds the values or a function callback which takes a pair of request and response parameters.
The way you have assigned var myItems = getData(); means the myItems is not one of these types. It will currently be an empty object because it is assigned before your Ajax call will complete.
Assuming you only need to load the data once, create the autocomplete in the success callback for your Ajax request;
$(document).ready(function(){
getData();
function getData(){
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
var myItems = {};
for(i = 0; i < json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
},
error : function(response){
console.log('error')
}
});
};
});

I actually tried going about this another way. i managed to pull all keys into a single array and use that as the source. the second box gets filled based on the value of the first box on the select event.
$(document).ready(function(){
var myItems = getData();
var keys = [];
for(var k in myItems){
keys.push(k);
}
$('#Item').autocomplete({
source: keys,
select : function(e,ui){
var value = myItems[ui.item.value];
$('#Rate').val(value);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log(myItems);
return myItems;
};

Related

fetch the associative array particular value with its key name

i have a function . here i am passing an array applicationTabId = {"twitter": "15", "dropbox": "14"}; "}; I have an ajax success function .In this the variable appName name holds the key names as twitter , dropbox etc. I got this from database as ajax response. i want to find the value associated with this from the array. variable appName holding the key names and iam getting it from database as ajax response. i need to check the corresponding value of this name from array.
function getapplicationlogouturl(applicationTabId) {
chrome.storage.sync.get("endpoint", function (obj) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
"sdcode": sdcode,
"type": "Chrome Fetch Application Logout Url"
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
timeout: globalTimeout,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
console.log(applicationTabId);
// o/p as {"twitter": "15", "dropbox": "14"}
console.log(appName);
//o/p as twitter
//dropbox
var tabid = applicationTabId.appName;
//var tabid = applicationTabId[appName];
console.log(tabid);
//o/p as undefined
console.log(appName+'---'+tabid);
if (appName in applicationTabId){
}
}
}
},
});
});
}
Apply loop like below:
$.each(applicationTabId, function(key,value){
console.log(key);
console.log(value);
});
Based on code you provided now, change your code like below:
function getapplicationlogouturl(applicationTabId) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
var tabid = applicationTabId[appName];
//print key value data in console to check working fine
console.log(appName+'---'+tabid);
}
}
},
});
}
Note:- var appName and var tabid value will be changed after each iteration happen.

Delete key/value pair from json array obtained from ajax response if key is found

I am fetching data from one list in sharepoint and storing it in json array to pass it onto another function to create a new item in Sharepoint list.The first function is:
$.ajax({
url: someSharepointListUrl,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
AllLinks: it.AllLinks,
LinkURL: it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
The item is stored in the list as as:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
The second function which fetches data from list after item is created is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
I need to match if a value exists in this newly created list Item.If yes then delete it eg Lin.
value of c(json array) here is:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
`
entry.AllLinks doesnt filter data here.AllLinks is undefined in entry.AllLinks.Please help
Use Array.findIndex() to find the desired value inside array, and use Array.splice() method to remove that object.

Object Jsonp array undefined value

I need help....I have this code:
var req = $.ajax( {
url:'http://zz33.infoucrso.com/WSCategorias.svc/cargarCategoria?callback=?',
dataType : "jsonp",
data: { nombre: val},
timeout : _timeOut
});
req.success(function(datos)
{
ProcesarCategorias(datos);
});
So I receive a object JSON and pass that object to the function ProcessarCategotias that have the next code:
function ProcesarCategorias(datos) {
var categoria = JSON.stringify(datos);
alert(categoria);
}
So that show an alert with the next information: {"IdCategoria":2,"Nombre":"Música"}, but I need to access only
the value of Nombre, if I do categoria[0] this show me an "{", If I do categoria["Nombre"] shows me an undefinied. I saw other questions but that doesn't work for me.
So thanks
Exchange
JSON.stringify(datos)
for
JSON.stringify(datos['Nombre'])

AJAX async returning wrong index

I have loop that cycles through multiple asynchronous AJAX calls. The call is fed the loop iteration as an index. When the call is completed, the data is stored in an array depending on the index.
However, the index returned in the success function is different than the index fed to the initial AJAX call. Is there a good way for the call to return the same index upon success that the call was initially fed?
var ptype = 'fp';
var pnum = 2;
var data = new Array();
for(var i = 1; i <= 5; i++){
call_general_forecast(ptype,i,pnum);
}
function call_general_forecast(ptype, i1, pnum1){
index = pnum1*5 + i1;
$.ajax({
url: '',
data : { stock_name : stock_name, pattern: ptype, specificity : i1},
type : 'get', //or 'post', but in your situation get is more appropriate,
dataType : 'json',
success : function(r) {
data[index] = r;
alert(index);
},
async: true
});
}
You're using index as a global var. Declare it as a local variable using the var keyword, and closure will do the rest for you. All success functions will have the correct index (with the same value they had when the request was being made).
function call_general_forecast(ptype, i1, pnum1){
var index = pnum1*5 + i1;
$.ajax({
url: '',
data : { stock_name : stock_name, pattern: ptype, specificity : i1},
type : 'get', //or 'post', but in your situation get is more appropriate,
dataType : 'json',
success : function(r) {
data[index] = r;
alert(index);
},
async: true
});
}

Show or hide jQuery elements according to boolean array

So I have the following code :
function aFunction(obj, myData)
{
$.ajax({
type: "POST",
url: 'myUrl',
data: myData,
async: true,
dataType: 'json',
success: function(data)
{
// ???
}
});
}
The data I receive (correctly) is an array of booleans. Now I need to show the jQuery objects according to each boolean : the number of jQuery objects and the size of the array is the same.
Now, the following works as my success callback :
success: function(data)
{
//obj.show();
var pcom_array = $.makeArray(obj);
for(var i = 0; i < data.length; i++)
{
console.log(pcom_array[i]);
if(data[i] === true)
{
pcom_array[i].style.display = '';
}
}
}
However, casting the jQuery object as an array and then iterating over the array doesn't feel very "jQuery-ish" to me. Is there a jQuery method or some other way that could smplify this?
You can use .toggle() - assuming obj is a jQuery wrapper containing a set of targeted elements in the same order as in the data array
success: function(data) {
obj.each(function(idx, el){
$(this).toggle(data[idx])
})
}

Categories

Resources