i want get json data from my Facebook page , and its a very thing okay , but empty display .
$(document).ready(function() {
var dmJSON = "https://graph.facebook.com/v2.4/me?fields=feed&debug=all&access_token=";
$.getJSON( dmJSON, function(data) {
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.feed.length; i++){
html += '<div>';
html += data.feed[i].message
html += '<br>';
html += data.feed[i].created_time
html += '</div>';
}
// append all the html variable to the ticker div.
$("#ticker").append(html);
});});
You need to look at the data you are getting. console.log the values you are trying to write out. Look at their parent objects when you get undefined.
It then rapidly becomes clear that data.feed is not an array. It is an object (and doesn't have a length).
It has a property called data that is an array.
Everywhere you have data.feed you should have data.feed.data.
Related
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.
I want to add a box with individual boxes inside it with every age when the function is run. I tried doing it by splitting the innerHTML and using the for loop on just the agebox section so it will loop and create a new age box each time and not create a whole outerbox as well everytime like if you try loop the entire thing. I thought this would work but now it creates an age box for each loop but its placed outside the outer box and i cant figure out how to get it to loop within the outer box. If i remove the loop and just create one innerHTML then the age boxes i made manually are inside the outer box so im assuming theres a problem with the actual splitting up of the innerHTML. Thanks in advance!!
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
el1.innerHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
el1.innerHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
el1.innerHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
}
You need to store the output content as a string and then append it to the DOM. Otherwise, the div will be auto-closed.
el1 = document.getElementById('farespage');
output = "<div id=\"outerbox\">"; //initialize output string
//build output string
for(var i=13; i<=18; i++){
output +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
output += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML = output; //output to DOM
View Fiddle
The line
el1.innerHTML += "<div id=\"outerbox\">";
is actually producing
<div id="outerbox"></div>
because most browsers will auto-close the HTML tags.
You should write all your HTML into a string buffer then append it with one big call; for example:
function Age(gender){
if (gender!==undefined){
el1 = document.getElementById('userdata');
el1.innerHTML += gender +"<br>";
}
el1 = document.getElementById('farespage');
// Magic begins here
var yourHTML = "";
yourHTML += "<div id=\"outerbox\">";
for(var i=13; i<=18; i++){
yourHTML +="<div class=\"agebox\" onclick=\"Relationship('"+i+"')\">"+i+"</div>";
}
yourHTML += "</div><button type=\"button\" onclick=\"goback('Gender')\">back</button>";
el1.innerHTML += yourHTML;
}
This has the added benefit of only touching the DOM once and not 7 times (which is generally a good thing).
Is there a better way of inserting somewhat complex html into a page other than the way I'm doing now? :
function display(friends) {
$(".row").empty();
$.each(friends, function(index, friend) {
var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
html += '<a href="/app/click/' + friend.id + '">';
html += '<img id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
html += '</a>';
html += '</div>';
$(".row").append(html);
});
Currently I have a list of facebook friends which are styled nicely. When a user searches through the friends, the entire content block is emptied and the result is appended (i'm using autocomplete). However the design could change and get more complex so i'm looking for a scalable way of doing what I have above.
Instead of creating the html inside the javascript, is there a smarter way of doing this? Perhaps with $.load() and passing each friend as an argument? But that seems very slow and server intensive if you have to list 100 friends.
One good way to go would be to use a templating engine, handlebars (as mentioned in the prev answer) is one of them. You could create your own as well if your scenario is simple as this. And another key thing is not to use append inside the loop, instead construct them to a temp array and add it to the DOM in the end. If your list is big and appending to the dom in the array can be expensive.
Add the template html with a placeholder for friendId
<script type="text/html" id="template">
<div class = "profileImage" style = "float:left;padding:20px; width:200px">
<a href = "/app/click/{{friendId}}">
<img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " />
</a>
</div>
</script>
And
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = [];
$.each(friends, function (index, friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
rows.push(templateHtml);
});
$row.html(rows); //Append them in the end
}
Demo
You could use $.map as well.
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = $.map(friends, function (friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
return templateHtml;
});
$row.html(rows);
}
A scalable solution would be to use a template engine and make the server returns JSON response.
Take a look at Handlebars.js http://handlebarsjs.com/
I'm creating my html tags on my Javascript because of some logic, but the expected result is not being displayed. I'm trying to get all checked checkboxes and display their names. I can pull the names and the checked checkboxes. But it is no rendering correctly. Here is my code:
var amenities = <%= #amenities_json.html_safe %>;
var appendAmenitiesAndFeatures= "<p class='p-tab-title3'>Amenities</p><table class='table-amenities-and-features'><tbody><tr>";
for(var i=0; i<amenitiesChecked.length;i++)
{
$.each(amenities, function(index, amenity){
if(amenity.id == amenitiesChecked[i])
{
appendAmenitiesAndFeatures += "<td><p class='p-tab-subtitle2><span> </span>" + amenity.name + "</p></td>";
}
});
}
appendAmenitiesAndFeatures += "</tr></tbody></table>";
$("#dv-amenities-and-features").html(appendAmenitiesAndFeatures);
When I check 3 checkboxes and alert their names, I can see the string of html tags being build properly. I can see 3 sets of tds in my alert. But when the page is being rendered. It only displays one. I really don't know why. I'm appending to a div and build my table using .html. Any ideas?
hum.... You miss a '
replace your line with this:
appendAmenitiesAndFeatures += "<td><p class='p-tab-subtitle2'><span> </span>" + amenity.name + "</p></td>";
I'm stuck trying to retreive categories id from a hyperlink in HTML5. First I have parsed a JSON link in HTML5 using jQuery.
My code:
HTML code:
jquery code:
<script src="jquery-1.8.3.min.js"></script>
<script>
$.getJSON('http://' '/storejson.php', function(data) {
var output="<ul>";
for (var i in data.items) {
output += "<li>" + data.items[i].categories_name + " " "</li>";
}
output += "</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
HTML code:
<div id="placeholder" align="justify">
I have given a hyperlink to placeholder like above. Categories are shown by parsing JSON but I want to show subcategories through hyperlink. So please tell me how can I acheive this?
What you could do is get the href from the a tag by
then pass link to your getjson when clicked or however best suits you and that will send the request to the php file, but keep in mind your php file has to also be set up to grab parameters passed in the url string from the href.
<script>
var link;
$("a").click(function(){link = $(this).attr("href")}); // get this inside a click event on the 'a' tag
alert(link);// to see the url being passed
$.getJSON(link, function(data) {
var output="<ul>";
for (var i in data.items) {
output += "<li>" + data.items[i].categories_name + " " "</li>";
}
output += "</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
CLICK // If you click here it should send the href data