Load JSON data into div based off of select option value - javascript

I'm trying to load data from a JSON file that is based off of the option that is selected by the user. I have it working but I know it can be written much more efficient and I'm having a hard time finding a good place to start. I'll include an example of my code below, but it's pulling in various counties based off of the state you choose. You'll notice though that I'm checking each value with an else if statement to load in the correct data. I'm sure there has to be a way to load what I need but without 49 other else if statements.
HTML:
<select id='test-select'>
<option>AL</option>
<option>AK</option>
<option>AZ</option>
</select>
JS:
var cities = [];
$.getJSON('/assets/shared/misc/counties.json', function(json) {
// push json to data to cities array
cities.push(json);
// map over each item item
$('.state-names').map(function(index) {
// load in json data based off of select option
$('#test-select').on('change', function() {
var target = $('#test-select option:selected').val();
console.log(target);
if (target == 'AL') {
$('.state-names').text(cities[0].AL);
} else if (target == 'AK') {
$('.state-names').text(cities[0].AK);
} else if (target == 'AZ') {
$('.state-names').text(cities[0].AZ);
} else if (target == 'AR') {
$('.state-names').text(cities[0].AR);
} // end else if block
}); // end test select function
}); // end map function
console.log(cities);
}); // end getJSON call
This is just the condensed version, but it's basically this plus many more options and else if's. Is there a way I can somehow set an index to whatever state is selected to match the key in the JSON file without having to make so many calls? Any help is greatly appreciated. If I left out any important details I can certainly share more information. Thanks guys.

You can simply use the value of target as property name:
$('.state-names').text(cities[0][target]);
See Access / process (nested) objects, arrays or JSON

Related

Cannot get the full json with request json

When I am actually entering the XXXX YYYY, then I am getting the players json code in my html page (around 150 values).
But when I am trying to use a function on the players list it somewhy does not contain all the 150 values and the try throws me into the catch error part, where I can see that players json has only 100 players inside there.
Any idea what could be the problem?
if(yourID === "XXXX" && targetID === "YYYY"){
return players;
}
try{
if(isUserAlive(yourID)){
if(targetID === ""){
return userTargetInfo(yourID);
}
var checkForMatch = getUserTarget(yourID);
if(checkForMatch === targetID){
killTarget(targetID);
getUser(yourID).targetID = getTargetTarget(targetID);
addScore(yourID);
return userTargetInfo(yourID);
//return getTargetTargetStats(targetID);
}else{
return "INVALID";
}
}else{
return "DEAD"
}
}catch(err){
console.log("Error",console.log(players))
return "INVALID"
}
Edit: Since I had no time, I created 2 websites and divided the database into 2 different databases, so it would work under 100 people on each. Did not have time to fix the error at this point. So I won't be choosing the solution to that since I won't be trying that any time soon.
Thank you for all your help!
Check the link api that you are using , it might have pagination integrated with it . in that case i will return certain number of object 1st and then you can re-request to get next batch . Most likely they might have a option to change the no of object returned (sometimes with max value)
I'm pretty sure body is returned as a string. Try changing it to an object so you can work with it easier.
Change:
players = body;
to:
players = JSON.parse(body);
I'm not sure the rest of your code, but you may want to add var on your players variable declaration because this looks like the first time you are setting it.
Research: namespace collisions
If you are still having issues, edit your question to include the response you are getting from console.log(JSON.parse(body));. You will be able to get more helpful answers. Personally, I am curious to see the keys such as:
{ query:
{ count: 1,
created: '2017-04-23T22:03:31Z',
lang: 'en-US',
results: { channel: [Object] } } }
If it's paginated, you should see some kind of cursor key in there, or prev and next along with some kind of totalCount.
Hope this helps.

Displaying Array Values From Local Storage

I am trying to display the values that have been stored in an array within local storage. I have been able to store the values in local storage and add other values on the click of a button but I cant retrieve the values back out and display them on a page.
This is my code that adds values to local storage.
$("#player1Link").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
if (a.indexOf(chosenPlayerId) === -1) {
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
alert("Pushed in");
} else {
alert("Already in favourites");
}
} else {
var a = [];
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
}
})
I want to be able to click a button to retrieve the values and display them on the page but I can figure out the code to go in this function.
$("#playerRetrieve").click(function() {});
If anyone could help it would be much appreciated.
I made a jsfiddle, it seems to work there: jsfiddle
try:
localStorage.getItem('player1Favourite');
or:
localStorage.player1Favourite
You might want to have a look at:
this topic
or at
Mozilla
I'm not exactly sure I understand you correctly, because if you just want to retrieve the values you can use the same code, just remove the insertion from your code and change the jQuery selector.
$("#playerRetrieve").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
// Do what you want with the values, which are now in a.
}
});

Can ajax be used for faceting/sorting?

I created a select from with popularity,high_to_low and low_to_high as options. I want the page to respond to these options dynamically using the ajax code
var http_option = createRequestObject();
function verifyRequest()
{
var option = document.getElementById("option").value;
if ( option )
{
var url = 'respond.pl?option='+option;
http_option.open('get', url );
http_option.onreadystatechange = handleResponse;
http_option.send(null);
}
}
function handleResponse()
{
if(http_option.readyState == 4 && http_option.status == 200)
{
var response = http_option.responseText; // Text returned FROM perl script
if(response) { // UPDATE ajaxTest content
document.getElementById("id_id").innerHTML = response;
}
}
If the value of the option is 1, images are displayed as stored in DB.
If the option is 2, images are to be displayed in descending order and
If the option is 3, images are to be displayed in ascending order
The respond.pl contain appropriate code for this sorting according to options and display images in a specified div tag.
The problem is that the page responds to the options only once and the next time on changing the option, the value of options shows "on" and not the numerals 1,2,3
I need this not only to sort images but also for faceting. If this is not the right option suggest the appropriate methods used for it.
It looks like your server-side program is returning HTML. And I think that's probably a mistake in this situation. I suggest returning JSON instead. Then, you can create an onChange event handler for your selector which simply re-orders the display. There are almost certainly a number of jQuery plugins that do this without you needing to write very much code.

Dynamically loading a database based on user text input

I have an autocomplete widget which needs to return options from a database of objects.
On doing so, once the user selects an item the widget will populate other hidden textfields with values from the particular object they chose. - All of this works and has been used on previous projects
However this particular database is far too big (44k+ objects, filesize is several mb and has taken far too long to load in practice) so we've tried various ways of splitting it up. So far the best has been by first letter of the object label.
As a result I'm trying to create a function which tracks the users input into a textfield and returns the first letter. This is then used to AJAX a file of that name (e.g. a.js).
That said I've never had much luck trying to track user input at this level and normally find that it takes a couple keystrokes for everything to get working when I'm trying to get it done on the first keystroke. Does anyone have any advice on a better way of going about this objective? Or why the process doesn't work straight away?
Here is my current non-working code to track the user input - it's used on page load:
function startupp(){
console.log("starting");
$("#_Q0_Q0_Q0").on("keyup", function(){
console.log("further starting!");
if($("#_Q0_Q0_Q0").val().length == 1){
console.log("more starting");
countryChange(($("#_Q0_Q0_Q0").val()[0]).toUpperCase());
}
else{
console.log("over or under");
}
});
}
And an example of the data (dummy values):
tags=[
{
label:"label",
code:"1",
refnum:"555555",
la:"888",
DCSF:"4444",
type:"Not applicable",
status:"Open",
UR:"1",
gRegion:"North West"
},
....
];
edit: fixes applied:
Changed startupp from .change(function) to .on("keyup", function) - keydown could also be used, this is personal preference for me.
Changed the autocomplete settings to have minLength: 4, - as the data starts loading from the first letter this gives it the few extra split ms to load the data before offering options and also cuts down how much data needs to be shown (helps for a couple of specific instances).
Changed how the source is gathered by changing the autocomplete setting to the following:
source: function(request, response) {
var results = $.ui.autocomplete.filter(tags, request.term);
response(results.slice(0, 20));
},
where tags is the array with the data.
all seems to be working now.
You should bind to keydown event:
function startupp(){
console.log("starting");
$("#_Q0_Q0_Q0").keydown(function(){
console.log("further starting!");
if($(this).length() == 1){
console.log("more starting");
countryChange(($(this).val()[0]).toUpperCase());
}
else{
console.log("over or under");
}
});
}

How to achieve this structure for an autocomplete feature?

Here is, more or less, the general workflow:
The user types something on a input element;
Onkeyup, it will grab values from our backend script, and choose one.
After choosing, onblur, we will grab that value and use it to query the database for some data,
With the data returned from the DB he will execute other commands on an external server.
Then it will grab that values and use them to fill some input elements that are there waiting to be filled in, once the user chooses is option from the autocomplete element.
With that data in place, the user can then change the values, and hit save for yet another "ajax adventure..."
So, here, we are on steps 1 and 2 only (so I believe):
This is what I have been able to accomplish with the help of this article. That I'm trying to understand and adapt.
//1) WHEN WILL verificaInput BE CALLED?
$(document).ready(function verificaInput(inputString) {
if (inputString.length == 0) {
$('#sugestoes').hide();
} else {
$.post('modelAutocompleteTeste.php',
{nomeDominio: $('#nome-dominio').val()},
function(dadosResposta){
if(inputString.length > 3) {
$('#sugestoes').show();
//2) WHAT SHOULD I PUT HERE?
}
},
"json"
);
}
}
About 1: We must NOT use inline js calls. Where should we call/use the events like onkeyup and onblur etc?
About 2:
view source
print?
function(dadosResposta){
This will contain the response from our server side script, if the input string is greater then 3, it will show our suggestions. Now, inside this suggestion I will need to populate some elements (<li>) containing ALL the data returned in json format from our server side script (it's PHP - using json_encode())?
If so, is this the proper place to loop over and create the li elements?
More then answers, I would like to ask for some advice; I'm lost and stuck.
To get you started...
$(document).ready(function() {
$('#your_input_field').bind('keyup', function() {
var theVal = $(this).val();
if (theVal.length > 3) {
verificaInput(theVal);
} else {
$('#sugestoes').hide();
}
});
});
function verificaInput(inputString) {
if (inputString.length == 0) {// this will never be true
$('#sugestoes').hide();// so this will never be necessary
} else {
$.post('modelAutocompleteTeste.php',
{nomeDominio: $('#nome-dominio').val()},
function(dadosResposta){
if(inputString.length > 3) {
$('#sugestoes').show();
//2 here you should include a function name that will allow interaction with the provided list
}
},
"json"
);
}
}

Categories