I have the following .js code but when i test the site, it only displays the wordings as seen in each but no contents. What i want to achieve at the end is to be able to display 5 posts and also add a link at the bottom to display more mosts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">entry.title</div>';
html += '<div class="entry">author</div>';
html += '<div class="entry">publishedDate</div>';
html += '<div class="entry">contentSnippet</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
If you know that your postlist is not null, and that each entry has properties 'title', 'author', 'publishedDate' and 'contentSnippet' try this:
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
try a $.each loop on data.responseData.feed.entries, see here for details
Related
Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
I have a Javascript ajax function that calls a PHP page to run a query and return an array of values which I then want to use to build a navigation list.
I can retrieve the results from the query, add them to an array and then encode them using json_encode but when they are returned to the ajax function I'm having problems extracting the values from the array and building the nav list.
Any help is very much appreciated.
My PHP Code is:
<?php
require_once("../includes/functions.inc");
$access_id = $_POST['access_id'];
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$query = "SELECT nav_link, nav_icon, nav_name FROM tbl_nav WHERE access_id <= " . $access_id;
$result = mysqli_query($mysqli, $query);
$rows = array();
while ($r = mysqli_fetch_array($result)){
$rows[] = $r;
}
echo json_encode($rows);
My Javascript code is
$(function(){
$.ajax({
type: "POST",
url: 'php_files/user_process/left_nav_generate.php',
dataType: 'JSON',
data: {
access_id: sessionStorage.getItem('access_id')
},
success: function(data) {
var obj = JSON.parse(data);
var headerNavItem = '';
var navBarList = '';
var footerNavItem = '';
headerNavItem = '<ul class="navigation navigation-main navigation-accordion">';
headerNavItem += '<li><i class="icon-home"></i><span>Dashboard</span></li>';
headerNavItem += '<li class="navigation-divider"></li>';
for (var i in obj) {
navBarList = '<li><a href="' + data[i].nav_link;
navBarList += '"><i class="' + data[i].nav_icon;
navBarList += '"></i> <span>' + data[i].nav_name;
navBarList += '</span></a></li>';
}
footerNavItem = '</ul>';
document.getElementById('leftNav').innerHTML = headerNavItem + navBarList + footerNavItem;
}
});
});
You need to replace mysql_fetch_array with mysql_fetch_assoc since you will use each record as an object later, and make a few corrections in your javascript (I commented them):
$(function(){
$.ajax({
type: "POST",
url: 'ajax.php',
dataType: 'JSON',
data: {
access_id: sessionStorage.getItem('access_id')
},
success: function(data) {
var obj = data; // JSON.parse(data); -> is not needed
var headerNavItem = '';
var navBarList = '';
var footerNavItem = '';
headerNavItem = '<ul class="navigation navigation-main navigation-accordion">';
headerNavItem += '<li><i class="icon-home"></i><span>Dashboard</span></li>';
headerNavItem += '<li class="navigation-divider"></li>';
for (var i in obj) {
// added concatenation from the start
// otherwise your list will always have just one line
navBarList += '<li><a href="' + data[i].nav_link;
navBarList += '"><i class="' + data[i].nav_icon;
navBarList += '"></i> <span>' + data[i].nav_name;
navBarList += '</span></a></li>';
}
footerNavItem = '</ul>';
document.getElementById('leftNav').innerHTML = headerNavItem + navBarList + footerNavItem;
}
});
});
And as commented, to avoid SQL injection is a good practice to convert the id to integer (or whatever the type of the access_id field in database):
$access_id = (int)$_POST['access_id'];
According to u_mulder's comment: Your data argument is already a JSON so remove JSON.parse(data);.
navBarList = '<li><a href="' + data[i].nav_link; The navBarList variable restarts for every item every item in the for statement. Change it to navBarList += '<li><a href="' + data[i].nav_link;.
You can use a simple variable to build your HTML navigation list.
Something like this:
$(function() {
var obj = [{
"nav_link": "nav_link1",
"nav_icon": "nav_icon1",
"nav_name": "Name 1"
}, {
"nav_link": "nav_link2",
"nav_icon": "nav_icon2",
"nav_name": "Name 2"
}, {
"nav_link": "nav_link3",
"nav_icon": "nav_icon3",
"nav_name": "Name 3"
}];
var html = '<ul class="navigation navigation-main navigation-accordion">';
html += '<li><i class="icon-home"></i><span>Dashboard</span></li>';
html += '<li class="navigation-divider"></li>';
for (var i in obj) {
html += '<li><a href="';
html += obj[i].nav_link;
html += '"><i class="';
html += obj[i].nav_icon;
html += '"></i> <span>';
html += obj[i].nav_name;
html += '</span></a></li>';
}
html += '</ul>';
document.getElementById('leftNav').innerHTML = html;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="leftNav"></div>
Hope this helps.
The data
[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"}
[{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}]
The code
var data =
[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"}][{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}];
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].title + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
this is the php response. i want to represent this data in html using js somehow how to do this
You have several mistakes in your code. As #RiggsFolly already mentioned your json is invalid. Furthermore you need to parse the data string as json object. Have a look at this code.
var data = '[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"},{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}]';
var htmlText = '';
var data = JSON.parse(data);
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].title + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
Since you are already using jQuery you could also create the div container in jQuery style.
var container = $('<div></div>').addClass('div-container');
I am using AJAX and Jquery to load a json object into my web page. It works great however 50-70% of the time it loads in the json data to my page twice, it appends the second set of data to my page, is there a good way to ensure that my data only loads once?
my initial thought was to make the json call synchronous instead of asynchronous but that doesn't sound right, is there a better way of doing it?
$('#myResource').click(function() {
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
});
});
});
Try
$('#myResource').unbind('click').click(function(){
})...
try to disable a button after click
$('#myResource').click(function() {
$('#myResource').prop('disabled' , true); //<<<<<<<<<<<<<<<< here
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
$('#myResource').prop('disabled' , false); //<<<<<<<<<<<<<<<<<<<<<<< here
});
});
});
with the help of some of the comments, the answer ended up being that i needed to unbind click at the beginning of the function, and leaving it unbound:
$('#myResource').click(function() {
$( "#myResource").unbind( "click" );
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
console.log('load everything');
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
});
});
});
I have the following code to load the first 10 blog posts and want to see how I can add a 'more...' text link at the end of the lists to load more posts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 10; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
The google feed API doesn't have the option to skip elements, its just a feed, so it loads all elements (as you already have defined num=... you already know that you can load more than 4 elements (which is the default).
To do what you want you would have to call the same request on button click and then implement some logic to compare if the new result contains elements which are not displayed on your page. If so, simply append them...