Retrieve specific data stored with JSON - javascript

I've used the code posted in THIS STACKOVERFLOW POST to build a prototype of a webbapp, but I can't make the second page show me the data with the format I want.
The code shows me the second page with all the data in a grid format, but I want to know how to make specific data with different formats (bold, italic, color).
For example, one string that I use is a "image.jpg" text to load an image of the user.
I've modified the first part of the code to:
$.each(info, function (i, valor) {
li += '<li><img src="img/'+ valor.foto +'"><h2><i>' + valor.cientifico + '</i></h2><p><b>Familia:</b> <i>'+ valor.familia +'</i> | <b>Subfamilia:</b> <i>'+ valor.subfamilia +'</i></p></li>';
});
to add specific values and apply different format (familia, subfamilia) and to insert the picture with the "foto" value.
Then the code continues:
$("#lista").append(li).promise().done(function () {
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
$("#resultado").data("info", info[this.id]);
$.mobile.changePage("#resultado");
});
$(this).listview("refresh");
});
});
$(document).on("pagebeforeshow", "#resultado", function () {
var info = $(this).data("info");
var info_view = "";
for (var key in info) {
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
$(this).find("[data-role=content]").html(info_view);
});
I know that the for (var key in info) is not what I'm looking for, but I don't know what code I have to use because I'm too new to unsderstand how to do it. How can I accomplish this?
The code next to info_view is HTML, right, but if I replace + key + with + familia + for example this doesnt works like before.
My question is how can I make to retrieve an specific data (for example the foto value) of the selected item listed in the first page? I want to be able to select wich items use. For example, I wanna make the id value invisible for the user, make the id value invisible, the name value in bold, and so on
Hope I was enough clear, sorry for my limited english and coding knowledge

Finnaly I've solved my own question.
For reference, what I do was deleted the
for (var key in info) {
and inside the info_view += part i've used info['value'] for each item I want to manipulate.
Hope this helps someone else.

Related

How do I encode/decode a fetch URL/JSON using javascript and flask

This is in reference to dynamically change options in a list by another list. Unfortunately, it all works except if the project name has a " or a #. Eg. Project name: '10" Centerline #3 Pipe'
I am a newbie to this and I have been cut/paste (learning) as I go along. If someone can help, it will be great. I am seen some things about escaping and encoding URI stuff but not sure where to put it in. The other problem is just understanding what happens past the onchange event.
I can get the list of project names from a previous list and it shows up in my HTML page. However, when I select the choices that have a ( " ) or a ( # ), the next populated list breaks.
Thanks in advance. I really, really appreciate the time if someone puts in a response.
Here is the javascript portion:
project_name_select.onchange = function(){
project_name = project_name_select.value;
fetch('/sr/new/project/' + project_name).then(function(response){
response.json().then(function(data) {
var areaHTML = '<option value="See List">Select Area</option>';
for (var state of data.project_area) {
areaHTML += '<option value="' + state.project_area + '">' + state.project_area + '</option>'
}
project_area_select.innerHTML = areaHTML;
});
});
}
Here is the flask portion:
#surveys.route("/sr/new/project/<get_project_name>")
def project(get_project_name):
project_dict, dict_type = choice_project_dict(get_project_name)
project_areaArray = []
for proj in project_dict:
ownerObj = {}
ownerObj['id'] = proj['company_name']
ownerObj['owner_company'] = proj['company_name']
ownerArray.append(ownerObj)
return jsonify({'project_area': project_areaArray})

How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.
Second Scenario:
In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.
Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.
So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){
var allow_to_open_condiments_conditional = $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();
if(allow_to_open_condiments_conditional == 'Yes') {
$('.conditional_table_hidden_noun').hide();
$('.conditional_table_hidden_condiments').show();
$('table#noun_chaining_order tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_condiments = $(this).find('td.condi_section_id').text();
$("table#customer_table_update_chain_order tbody").html('');
$('#customer_modal_update_chain_order').modal('show');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#customer_table_update_chain_order tbody').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
},
error:function(response){
console.log(response);
}
});
}
else
{
}
});
So the question will be, How to stop appending multiple times once I force double click the table row?
I see simple solutions here.
When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
(button)to prevent it from another click.
Check your database for multiple records.
Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?

executing JS function and define variable from html

What I have is a page which is gathering a large list of data via jQuery. I am trying to limit the amount of results shown to a variable, and change the results shown on the list to create a false-page effect. Everything works via the same JS function, and relies on 1 variable to make everything work. Simple. I've removed all of the extra code to simplify everything
function myFunction() { var page = 1; console.log(page); }
I am looking for a way to call on this function, but change the variable 'page' from within html. Something along the lines of:
2
I have been looking on google (and still am) I just can't seem to find what I am looking for. I'm trying to avoid multiple pages/refreshing as this element is going to be used for a larger project on the same page.
UPDATE: I managed to pass the intended values through to a JS function like so...
function myFunction(page) { console.log(page); }
...and...
<input type='button' onclick='myFunction(value)' value='input page number'>
This seems the simplest way of doing what I need, what do you think?
Thanks for your help btw guys.
To do this you will need to move the page variable to be a parameter of myFunction
function myFunction(page) { console.log(page); }
Then you can just pass in whatever page number you would like
2
Sure, you can add the data-url attribute to your markup and select on the .link class to fetch the data-url attribute for each element thats part of that class.
I'm trying to avoid multiple pages/refreshing as this element is going
to be used for a larger project on the same page.
Sounds like you also want an AJAX solution.
$(document).ready( function()
{
//Add this on your call.html page
$(".link").click(function()
{
//location of test JSON file
var root = 'https://jsonplaceholder.typicode.com';
//your custom attribute acting as your 'variable'
var page = $(this).attr('data-url');
console.log("page = " + page);
//remove any previous html from the modal
$(".modal-content").empty();
//send a request to the server to retrieve your pages
$.ajax(
{
method: "GET",
//this should be updated with location of file
url: root + '/posts/' + page,
//if server request to get page was successful
success: function(result)
{
console.log(result);
var res = result;
var content = "<div class='panel-default'><div class='panel-heading'><h3 class='panel-title'>" + res.title + "</h3></div><i><div class='panel-body'>''" + res.body + "''</i></div><p><u> Master Yoda, (2017)</u></p><p class='page'> Page: " + page + "</p></div>";
$(".modal-content").html(content);
},
//otherwise do this
error: function(result)
{
$(".modal-content").html("<div class='error'><span><b> Failed to retrieve data </b></span><p> try again later </p></div>");
}
});
});
});
.error
{
border: 2px dotted red;
margin: 5px;
}
a
{
font-size: 20px;
}
.page
{
text-align: left;
padding: 0 15px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<a class="link" data-url="1" data-toggle="modal" data-target="#Modal" href="test.html">Show Page 1</a>
<br />
<a class="link" data-url="2" data-toggle="modal" data-target="#Modal" href="">Show Page 2</a>
<div id="Modal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
I seem to have figured out how to do this. I wanted to stray from using lots of libraries in the project and just wanted to keep things simple, using the above answers for guidance (and a little more digging), basically my end goal was to use jQuery to obtain a long list of data, and format this data into a multiple page list (for which I used a table for formatting purposes). Let's say it's a list of names. The JSON results output as:
[{"first_name":"Bob"},{"last_name":"Jones"}] // (key, value)
But when I passed this through to the HTML Table it was just displaying 1000s of results in a single list, and formatting the list was a pain. This was my solution:
<script>
var pageNum = ""; // define Page Number variable for later.
var resLimit = 35; // variable to specify the number of results per page
function updateList () {
$.getJSON(" Location of JSON results ", function(data) {
var pageCount = Math.round(data.length/resLimit); // calculate number of pages
var auto_id = ((pageNum-1)*resLimit) // use variables to give each result an id
var newListData = ""; // define this for use later
then define and pass "new list data" to HTML Table:
var newListData = "";
$.each(data.slice(auto_id, (pageNum*resLimit)), function(key, value) {
auto_id++;
newListData += '<tr>';
newListData += '<td class="id">' + audo_id + '</td>';
newListData += '<td class="id">' + value.first_name + '</td>';
newListData += '<td class="id">' + value.last_name + '</td>';
newListData += '</tr>';
});
$('# ID of table, data will replace existing rows ').html(newListData);
At this point if you set the value of pageNum to 1 you should see the first 35 results on the list, all with auto-incremented ID numbers. If you change it to 2 and refresh the page you should see the next 35, with the ID numbers following on from the first page.
Next I needed to create a button for each of the pages:
$('# ID of table, data will replace existing rows ').html(newListData);
function createButtons() {
var buttonArray = "";
for(i=0, x=pageCount; i<x; i++) {
buttonArray += '<input type="button" onclick="changePage('
+ (i + 1) + ')" value="' + (i + 1) + '">';
}
$('# ID of Span tags for button container ').html(buttonArray); }
createButtons();
}); }
</script>
Then create changePage() and a function to refresh the data in the list automatically without messing things up
<script>
var pageNum = "";
function changePage(page) {
if (pageNum < 1) { pageNum = 1; } // set pageNum when the page loads
if (page > 0) { pageNum = page; } // overwrite pageNum when 'page' variable is defined
updateList(); }
changePage(); // initialise to prevent delayed display on page load
// refresh function:
function refreshData() {
changePage(0); // define 'page' as 0 so that pageNum is not overwritten
window.setTimeout(refreshData, 5000); } // loop this function every 5 seconds to
refreshData(); //-- keep this list populated with current data.
And that should just about do it! At least it's working for me but I might have missed something (hopefully not lol). Hope this helps someone theres quite a few things involved in this that could be extrapolated and used elsewhere :)
thanks for help everyone.

How to add last.fm now playing into my site using Api

Hi guys i been trying to figure out for a long time but i suck at this, i found this code on google and i added it adn changed what i need but still doesnt work i really need this for my site: http://www.balkan-party.cf/
I found code here: http://www.samkitson.co.uk/using-json-to-access-last-fm-recently-played-tracks/
My last.fm username i need in js: alicajdin AND
Api key: 24f6b03517ad9984de417be5d10e150b
This is what i did:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=alicajdin&api_key=24f6b03517ad9984de417be5d10e150b&limit=2&format=json&callback=?", function(data) {
var html = ''; // we declare the variable that we'll be using to store our information
var counter = 1; // we declare a counter variable to use with the if statement in order to limit the result to 1
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
} // close the if statement
counter++ // add 1 to the counter variable each time the each loop runs
}); // close each loop
$('.listening-to h5').append(html); // print the information to the document - here I look for the h5 tag inside the div with a class of 'listening-to' and use the jQuery append method to insert the information we've stored in the html variable inside the h5 tag.
}); // close JSON call
});
I created that file and i tried to add on head section, footer section but it wont show recent tracks.
And yea i have scroblr installed on google crome
below </script> add the following code:
<div class="listening-to"></div>
then remove "h5" on
"$('.listening-to h5').append(html);"
so your code like this:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=2&format=json&callback=?", function(data) {
var html = '';
var counter = 1;
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
}
counter++
});
$('.listening-to').append(html);
});
});
</script>
<div class="listening-to"></div>
Hope you can help. Sorry, my English is very Bad (Google Translate)

Parsing in jquery

I am trying to parse what I am getting JQuery to show data ! I am consuming data from an API , but I am getting an error .
Can I do a Loop on JQuery this way ?
$.each(data.results, function (i, item) { // on this line
var Name = item.name;
var Date = item.auditInfo.dateCreated;
var Creator = item.creator.display;
$htmlstring.append($('<li/>').append('<p>Test</p>'));
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
}); $('#afficher').html($htmlstring);
I am sharing code on JSFiddle (Check drug_omrsRestCall function ) :
http://jsfiddle.net/zTXyq/23/
As #adeneo commented on the question, the concept is right but you should be careful about what element you are appending HTML content to.
With this snippet of your code:
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
(BTW, it is missing two plus signs for a correct concatenation, I hope that's not the error you are getting).
you append a DIV to the UL and you actually want to append it to the LI, for example:
$('<li />').append("<p>Test</p>")
.append("<div class='title'> Info : " + Name + Date + Creator + "</div>")
.appendTo($htmlstring);
Check this fiddle for a working solution of your issue:
http://jsfiddle.net/d3dcj/2/

Categories