Autocomplete in jQuery 1.4.2 jQuery UI 1.8.3 - javascript

I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris

I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});

Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().

try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

Using JSON Array with AJAX

I'm trying to append parts of a JSON array (that is received from a server) to a table after clicking a button. Somehow I can't add the parts of the json array to this table.
This is the JSON Array received from the server:
{"pass": [
{
"Date":"01.01.2001",
"Time":"14:20",
"ID":"1234",
"Name":"Sat",
"elevation":"168.9°",
"losTime":"04:31"
},
{
"Date":"01.01.2002",
"Time":"14:30",
"ID":"1235",
"Name":"Com",
"elevation":"16.9°",
"losTime":"04:25"
}
]}
The Code is the following:
$(document).ready(function(){
$("#submit-button").click(function() {
$.ajax({
url: "../rest/passdata",
type: "GET",
data: {
satellite: document.getElementById("satellite").value,
startDate: document.getElementById("startDate").value,
startTime: document.getElementById("startTime").value,
endDate: document.getElementById("endDate").value,
endTime: document.getElementById("endTime").value
},
dataType: "json",
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(response) {
var arr = response;
$("#pd-table").find("#pd-body").empty();
$.each(arr, function(i, value){
var checkbox = $('<input type="checkbox"/>');
$("#pd-table").find("#pd-body")
.append($("<tr>"))
.append($("<td>").append(checkbox))
.append($("<td>").append(arr.pass.ID[i]))
.append($("<td>").append(arr.pass.Date[i]))
.append($("<td>").append(arr.pass.Time[i]))
.append($("<td>").append(arr.pass.losTime[i]))
.append($("<td>").append(arr.pass.Name[i]))
.append($("<td>").append(arr.pass.elevation[i]))
.append($("</tr>"))
The checkbox gets added to the table, which makes me think that reading out the array does not work the way it should.
I already tried to parse the response from the server but that also didn't work out and in that case even the checkbox didn't get added to the table.
I hope someone can help me out!
Several problems:
You want to loop over the array in response.pass not the whole object
You are appending the cells to the <tbody> not to the new row.
You can not append a closing tag. The DOM only accepts complete elements and has no understanding of appending a closing tag in a jQuery object. The full element gets created when you do $('<tagname>')
Simplified version:
var arr = response.pass;
var $tbody = $("#pd-body").empty();
$.each(arr, function(i, value) {
var checkbox = $('<input type="checkbox"/>');
var $row = $("<tr>")
// append cells to the new row
.append($("<td>").append(checkbox))
.append($("<td>").text(value.ID))
.append($("<td>").text(value.Date))
.append($("<td>").text(value.Time))
.append($("<td>").text(value.losTime))
.append($("<td>").text(value.Name))
.append($("<td>").text(value.elevation));
// append complete row
$tbody.append($row)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="pd-table" border=1>
<tbody id="pd-body">
</tbody>
</table>
<script>
var response = {
"pass": [{
"Date": "01.01.2001",
"Time": "14:20",
"ID": "1234",
"Name": "Sat",
"elevation": "168.9°",
"losTime": "04:31"
},
{
"Date": "01.01.2002",
"Time": "14:30",
"ID": "1235",
"Name": "Com",
"elevation": "16.9°",
"losTime": "04:25"
}
]
}
</script>

How to split json array from ajax GET into objects?

Good night everyone.
I've seen this question answered in other posts, but no answer works for me, I'm new in ajax/json and I'm a bit lost.
I have this ajax call that returns me a JSON array:
$.ajax({
type: "GET",
url: common.RestURL.index,
dataType: 'json'
}).done(parameters => {
//Fill parameters
drawSettings(parameters);
}).fail(function (jqXHR, textStatus, error) {
showMsg(jqXHR.responseJSON.message,
"Error",
"error");
});
This is the exact json object to return:
"config": [
{
"configDescription": "description1",
"configValue": "value1",
"configKey": "key1",
"idCompany": "company1",
"appConfigurationId": "config1",
"configType": "List"
},
{
"configDescription": "description2",
"configValue": "value2",
"configKey": "key2",
"idCompany": "company2",
"appConfigurationId": "config2",
"configType": "Date"
},
{
"configDescription": "description3",
"configValue": "value3",
"configKey": "key3",
"idCompany": "company3",
"appConfigurationId": "config3",
"configType": "String"
},
{
"configDescription": "description4",
"configValue": "value4",
"configKey": "key4",
"idCompany": "company4",
"appConfigurationId": "config4",
"configType": "Boolean"
}]
So when the ajax call gets the json array, it calls another method that works with each of the objects in the array, but when I try to create each object, they are created empty and I can't find the problem, this is the function I'm talking about:
function drawSettings(parameters) {
if (!$.isArray(parameters)) {
parameters = [parameters];
}
//Fill params in div
$.each(parameters, function (key, value) {
//Parameter to draw
console.log("value .........................." + value.configDescription);
let param = new Parameter(value);
console.log("objetooo ------------ " + param.configDescription);
The Parameter class is a simple class with the attributes of the json ojects and the logs show the attributes with "undefined" value.
Can please someone help me understand and solve the problem?
Thanks to everyone in advance!

Twitter Typeahead/Bloodhound Suggestions from Ajax-Source: how manage multiple values?

I'm using typeahead/bloodhound for suggestions pulling from an ajax source:
var protags = new Bloodhound({
datumTokenizer: function(protags) {
return Bloodhound.tokenizers.whitespace(protags.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/ajax/getinfo.php?q=%QUERY',
wildcard: '%QUERY',
filter: function(response) {
return response.protags;
}
}
});
JSON result from getinfo.php looks like this:
{
"protags": [
{"tag": {
"tagid": "1",
"tagtitle": "titleone"}
},
{"tag": {
"tagid": "2",
"tagtitle": "titletwo"}
},
{"tag": {
"tagid": "3",
"tagtitle": "titlethree"}
}]}
I'm able to retrieve all the information i want (tagtitle AND tagid) and display it using:
$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
},
{
name: 'protags',
displayKey: function(protags) {
return protags.tag.tagtitle+'-'+protags.tag.tagid;
},
source: protags.ttAdapter()
});
But i'm confused about that: how can i display just the tagtitle in the suggestion field, but getting the protags.tag.tagid as well for more serverside actions?
Use the :select event (v 0.11.x), or :selected event (v.0.10.x). Read the bloodhound/typeahead docs as they made a lot of changes between 0.10.x and 0.11.x
I'm using 0.10.5 and in my case it looks like this:
EDIT: looking at your json, I'm not sure what data goes into template and :selected function. You may need to use data.protags.tag etc
$(selector).typeahead(
// options, key, source etc
templates: {
suggestion: function (data) {
return '<div class="tt-name">' + data.tag.tagtitle + '</div>';
}
}
// end of options
)
.on('typeahead:selected',
function(event, data) {
// you should be able to get your data here, if I'm correct like so:
console.log(data.tag.tagid);
}
);

Howto convert JSON to Array

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

Categories

Resources