getjson() jquery dropdown not working - javascript

I have the following json file:
{
"viewport_size":
{"display_name":"VIEWPORT SIZE:",
"name":"viewport_size",
"format":"number",
"type":"dropdown",
"dflt":"640 * 480",
"values":["800*600","1280*720","1920*1080"],
"isMandatory":"true"},
"framerate":
{"display_name":"FRAMERATE:",
"name":"fps",
"format":"number",
"type":"dropdown",
"dflt":"30",
"values":["45","60","90"],
"isMandatory":"true"},
"pattern_resolution":
{ "display_name":"PATTERN RESOLUTION:",
"name":"resoln",
"format":"number",
"type":"dropdown",
"dflt":"8",
"values":["16","32","64"],
"isMandatory":"true"}
}
I am tryin to populate the dropdown list in my js file using getJSON()
var INPUT_TEXT='<input type="text"/>';
var INPUT_RADIO='<input type="radio"/>';
var INPUT_CHECKBOX='<input type="checkbox"/>';
var INPUT_DROPDOWN='<select id="items"></select>';
var SUBMIT_BUTTON='<input type="button" value="SUBMIT"/>';
var NEWLINE='<br></br>';
$.getJSON('json_input/client_settings_input.json',function(clientData)
{
$.each(clientData,function(i,feild)
{
if(this.type=="dropdown")
{
var html = '';
var len = feild.values.length;
//alert('lenght is'+len);
for (var i = 0; i< len; i++){
//alert('inside for');
html += '<option>'+ feild.values[i]+'</option>';
}
$('body #tabs #tabs-2 client').append (this.display_name).append(INPUT_DROPDOWN).append(html).append(NEWLINE);
}
});
$('body #tabs #tabs-2 #client').append(SUBMIT_BUTTON);
});
but I am not able to view the dropdown list and the values...Kindly point out where I am going wrong..
I want to populate like this VIEWPORT: dropdownlist values
FRAMERATE:dropdownlist values
PATTERN_RESOLUTION:dropdownlist values

Try
.append($(INPUT_DROPDOWN).html(html))
istead of .append(INPUT_DROPDOWN).append(html)
options must be in the select but you insert in the same level than the select.
see http://jsfiddle.net/q7fWt/

Try adding the parameter "jsoncallback=?" to your URL
$.getJSON('json_input/client_settings_input.json?jsoncallback=?',function(clientData)
jQuery will substitute the last questionmark, after the jsoncallback parameter, with an ID.
This ID will then be used on server side to create a response that will start with a function named from the ID value.
That would result in a response that would look something like this:
jQuery16205149872086476535_1314088378455({
"viewport_size":
{"display_name":"VIEWPORT SIZE:",
"name":"viewport_size",
"format":"number",
"type":"dropdown",
"dflt":"640 * 480",
"values":["800*600","1280*720","1920*1080"],
"isMandatory":"true"},
"framerate":
{"display_name":"FRAMERATE:",
"name":"fps",
"format":"number",
"type":"dropdown",
"dflt":"30",
"values":["45","60","90"],
"isMandatory":"true"},
"pattern_resolution":
{ "display_name":"PATTERN RESOLUTION:",
"name":"resoln",
"format":"number",
"type":"dropdown",
"dflt":"8",
"values":["16","32","64"],
"isMandatory":"true"}
});
So in a short answer, if your json response is NOT wrapped in this function name the callback function will not fire, instead you will get an error which you could see this way:
$.getJSON('json_input/client_settings_input.json?jsoncallback=?',function(clientData) {
//your code
}).error(function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + " errorThrown: " + errorThrown);
})
Hope this helps
Patrik

Related

loop posting ajax results until they are all posted

the below code works great for displaying in my first file
$.ajax({
url : "http://localhost/website/files/userstuff/files/",
asynch : false,
cache : false,
success: function (data) {
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("#filestable").html(displayfilestable)
$("filestable, table").append(adddata);
console.log(adddata)
}
});
}
});
this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance
enter image description here
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.
HTML
<div>
sad1.pdf<br>
sad2.pdf<br>
sad3.pdf
<div id="filestable"></div>
</div>
JAVASCRIPT
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("filestable, table").append(adddata);
console.log(adddata)
}
});
AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/

Get all cards from Trello and store details

I'm trying to write some simple Javascript that uses the Trello API to get all boards / lists / cards from my account and add them into an sortable table (using the Datatables jquery plugin).
I've so far managed to write a jsfiddle that gets all this information and writes it to a page, but I can't work out how to store all this information into some sort of data structure that can then be passed to the datatable plugin.
This is the fiddle I have so far that gets the data from Trello:
JS Fiddle Link
var carddata = [];
Trello.members.get("me", function(member) {
$("#fullName").text(member.fullName);
var boardUrl = "";
boardUrl = "members/me/boards";
Trello.get(boardUrl, function(boards) {
$.each(boards, function(ix, board) {
Trello.get("/boards/" + board.id + "/lists", function(lists) {
$.each(lists, function(ix, list) {
Trello.get("lists/" + list.id + "/cards", function(cards) {
$.each(cards, function(ix, card) {
console.log("boardname: " + board.name + "; list name: " + list.name + "; card name: " + card.name);
carddata.push(
"boardname: " + board.name +
"; list name: " + list.name +
"; card name: " + card.name
);
var $tablerow = "";
$tablerow = $(
"<tr><td>" + board.name +
"</td><td>" + list.name +
"</td><td>" + card.name +
"</td></tr>"
).appendTo("#table_body");
});
/*
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
*/
});
});
});
});
});
});
// **** carddata array is empty at this point ****
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
It loops through all boards, lists and cards and currently adds what it finds to a html table (and also an array). I then use the Datatables plugin to change that HTML table into a sortable table.
However the plugin is seeing the HTML table as empty (from what I can see), I presume this is because of something like the plugin code being called before the Javascript builds up the table in HTML.
So instead I planned to add all the data into an array, and then pass that array into the datatable as a datasource, but I can 't see how to make the array accessible outside the very inner loop. From doing some searches I think this is to do with closures and scope but I'm struggling to understand how they work (I'm very new to Javascript).
Is anyone able to help me get this basic code working and show me what I'm doing wrong?
Thanks,
David.
The following code snippet demonstrate how to add data to data table after table created. For how to wait for all asyn requests completed, setTimeout is used to simulate Trello.get method for the asyn behavior.
var boardHash = {};
var listHash = {};
var updateLoggedIn = function() {
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var loadCardData = function(){
var carddata = [];
var loadMember = function() {
setTimeout(function(){
console.log("Member loaded");
loadBoard();
},2000);
}
var loadBoard = function() {
setTimeout(function(){
console.log("Boards loaded");
var listPromises = [];
loadList(["boardA","boardB","boardC"],listPromises);
$.when.apply($, listPromises).then(function(){
table.rows.add(carddata).draw("");
});
},1000);
};
var loadList = function(boards,listPromises){
$.each(boards,function(boardIndex, boardValue){
var listDefered = $.Deferred();
listPromises.push(listDefered.promise());
setTimeout(function(){
console.log(boardValue+" lists loaded");
var cardPromises = [];
loadCard(["listA","listA","listC"],boardValue,cardPromises);
$.when.apply($, cardPromises).then(function(){
listDefered.resolve();
});
},(boardIndex+1)*900);
});
};
var loadCard = function(lists,boardValue,cardPromises){
$.each(["listA","listA","listC"],function(listIndex, listValue){
var cardDefered = $.Deferred();
cardPromises.push(cardDefered.promise());
setTimeout(function(){
console.log(boardValue+" "+listValue+" cards loaded");
$.each(["cardA","cardB","cardC"],function(cardIndex, cardValue){
carddata.push({
"boardName":boardValue,
"listName":listValue,
"cardName":cardValue
});
});
cardDefered.resolve();
},(listIndex+1)*800);
});
};
loadMember();
};
var logout = function() {
updateLoggedIn();
};
$("#connectLink")
.click(function() {
loadCardData();
});
$("#disconnect").click(logout);
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var table = null;
$(document).ready( function () {
table = $('#table_id').DataTable({
columns: [
{ data: 'boardName' },
{ data: 'listName' },
{ data: 'cardName' }
]
});
} );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="loggedout">
<a id="connectLink" href="#">Connect To Trello</a>
</div>
</head>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
<a id="disconnect" href="#">Log Out</a>
</div>
<div id="output"></div>
</div>
<table id="table_id" class="display" border=1>
<thead>
<tr>
<th>Board</th>
<th>List</th>
<th>Card</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="console-log"></div>
</html>
For adding data to data table
So in your code, add the columns options to the data table, and use rows.add method to add data to data table when all ajax request are done.
Wait for all ajax request completed
The most tricky part is how to ensure all response are done, this can be achieved by $.Deferred() and $.when.apply, see JQuery document and What does $.when.apply($, someArray) do? for more details.

Bootstrap typeahed is one character behind using jquery

I am using bootstrap typeahead (GitHub) to create search forms. After user inputs something I am doing elasticsearch query using elasticsearch.js and returning results. The problem is that results displayed in typeahead are always one character behind, not suggesting correct values.
Typeahead input:
<input type="text" data-provide="typeahead" class="form-control typeahead" id="searchInputId" placeholder="Search" autocomplete="off">
Here is my code:
var elasticsearchAddress = "exampleserver.com:9200";
var elasticsearchClient = createElasticsearchClient(elasticsearchAddress);
var data = [];
$("#searchInputId").typeahead({ source:data, items:10, fitToElement:true });
$("#searchInputId").on("input", function(){
var searchTerm = $("#searchInputId").val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function () {
$("#searchInputId").data('typeahead').source = getElasticsearchSearchResultsArray();
});
});
elasticsearchMathPhrasePrefixSearch() function
function elasticsearchMathPhrasePrefixSearch(client, searchPhrase, callback) {
console.log("Searching for: " + searchPhrase);
client.search({
body: {
"query": {
"match_phrase_prefix": {
"accountName": searchPhrase
}
}
}
}, function (error, response) {
if (error) {
console.trace('ELASTICSEARCH: Search query failed');
} else {
console.log('ELASTICSEARCH: Search query OK');
var doc = response.hits.hits;
elasticsearchSearchResultsArray = getDocs(doc);
}
callback();
});
}
getDocs() function
function getDocs(doc){
var searchResultsArray=[];
for(var i = 0; i < doc.length; i++){
searchResultsArray.push(doc[i]._source.accountName);
}
return searchResultsArray;
getElasticsearchSearchResultsArray() function
function getElasticsearchSearchResultsArray(){
return elasticsearchSearchResultsArray;
}
elasticsearchSearchResultsArray is a global array that holds the results. Because of the JS async nature I had no other idea to make it work.
EDIT:
Ok, I modified my code so the source is updated correctly with help of this Issue #1997. But now I have got another problem. The typeahead dropdown is not displayed when I type.
My new code:
var empty = [];
$("#searchInputId").typeahead({ source:empty, items:10, fitToElement:true });
$("#searchInputId").on("keyup", function(ev){
ev.stopPropagation();
ev.preventDefault();
//filter out up/down, tab, enter, and escape keys
if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){
var self = $(this);
//set typeahead source to empty
self.data('typeahead').source = [];
//active used so we aren't triggering duplicate keyup events
if( !self.data('active') && self.val().length > 0){
self.data('active', true);
//Do data request. Insert your own API logic here.
var searchTerm = self.val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function() {
//set this to true when your callback executes
self.data('active',true);
//set your results into the typehead's source
self.data('typeahead').source = getElasticsearchSearchResultsArray();
//trigger keyup on the typeahead to make it search
self.trigger('keyup');
//All done, set to false to prepare for the next remote query.
self.data('active', false);
});
}
}
});
Try to use on("keyup") instead. input is 1 character behind.
Ok, I resolved it myself. I switched from bootstrap3-typeahead to jQuery UI Autocomplete. It is working great and the script is much smaller.
New code:
$("#searchInputId").on("keydown", function () {
$("#searchInputId").autocomplete({
source: function(request, response) {
var searchTerm = $("#searchInputId").val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function (){
response(getElasticsearchSearchResultsArray());
});
}
});
});

Autocomplete on wrong form field

I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>

JQUERY SELECT AJAX

the following code works fine for me to show various sql-results after change a select-field:
$(document).ready(function() {
$('#main_kat').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
$.post('/ajax/joe.php?qid=<? echo $row_job['sub_quali'];?>', { value : val}, populateDropdown, 'html');
$("#send").prop('disabled', false);
}
function populateDropdown(data) {
if (data != 'error') {
$('#subcat').html(data);
}
}
my problem: for a new insert everything is great because i have to select manualy, but if i use this code for my update form, i want to have opend my div #subcat allready.
i tried following at the beginning:
kat = $('#main_kat').val();
getDropdownOptions(kat);
kat is set (checked) via alert, but the function will not be fired... where is my mistake ?
Thanks
you can not just call the function because you are using it with this.
kat = $('#main_kat').val();
getDropdownOptions(kat);
function getDropdownOptions() {
var val = $(this).val();
change to:
getDropdownOptions();
function getDropdownOptions() {
var val = $(document.getElementById('main_kat')).val();
It will probably work fine if you ensure that the this reference points to the correct object when you call the function. Instead of passing kat as a parameter you could just call the getDropdownOptions method with the following code:
getDropdownOptions.apply(kat);
I'll recommend you to replace your getDropdownOptions function by this:
function getDropdownOptions(val) {
val = val || $('#main_kat').val();
$.post('/ajax/joe.php?qid=<? echo $row_job['sub_quali'];?>', { value : val}, populateDropdown, 'html');
$("#send").prop('disabled', false);
}

Categories

Resources