Insert data from API into DOM - javascript

I retrieve data from an API and I want to get it in my bootstrap layout.
$.ajax({
url: 'https://api.import.io/store/connector/b5caf0ef-1e6b-4fba-9fa4-21e475196673/_query?input=webpage/url:http%3A%2F%2Fnuzzel.com%2FWAStatzz%3Fsort%3Dfriends%26when%3D2&&_apikey=<myKey>'
}).done(function(data) {
console.log(data);
var html = "";
$.each(data.results, function(index, item) {
html += "<div class='row'>";
html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
html += "<span class='item-description'>" + item.description + "</span>";
html += "</div>";
});
setTimeout(function() {
$(".container").append(html);
}, 1500);
});
I tried this, but it is not working? why?

Well, just add a container to your DOM where the markup should be added.
<div class="js-table-container"></div>
And then add the html to this container
var html = "";
$.each(data.results, function(index, item) {
html += "<div class='row'>";
html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
html += "<span class='item-description'>" + item.description + "</span>";
html += "</div>";
});
$('.js-table-container').html(html);
If i understand your problem correctly, that's all.

If you what this data to come after or before an element in Dom use jquery insertAfter or insertBefore. Why are you using timeout function?
You can directly add to Dom after processing.
> $.ajax({
> url: 'https://api.import.io/store/connector/b5caf0ef-1e6b-4fba-9fa4-21e475196673/_query?input=webpage/url:http%3A%2F%2Fnuzzel.com%2FWAStatzz%3Fsort%3Dfriends%26when%3D2&&_apikey=<myKey>'
> }).done(function(data) {
> console.log(data);
>
> var html = "";
> $.each(data.results, function(index, item) {
> html += "<div class='row'>";
> html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
> html += "<span class='item-description'>" + item.description + "</span>";
> html += "</div>";
> });
> // if you want to load all data inside this container use html
> $(".container").html(html);
> // if you want to load after this
> $(".container").insertAfter(html);
> // if you want before this
> $(".container").insertBefore(html);

Related

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

How to add links to the table using jquery?

so I have this file called jsonkategoria.json with categories names and links. I want to display these in a table. Somehow (I'm begginer in jQuery programing) my table displays names only. I think the problem may be within the quotes in tag. This is how the table looks in browser. There's no link to the page. I've tried many options with adding each line separately (I mean :
categories_data += '<a href=';
categories_data += '"';
categories_data += value.links;
etc.)
Here's my jQuery code:
$(document).ready(function(){
$.getJSON("jsonkategoria.json", function(data){
var categories_data = '';
$.each(data, function(key, value){
categories_data += '<tr>';
categories_data += '<a href="'+value.link+'" >';
categories_data += '<td>'+value.nazwa+'</td>';
categories_data += '</a>';
categories_data += '</tr>';
});
$('#categories_tab').append(categories_data);
});
});
Here you go with a solution
$(document).ready(function(){
$.getJSON("jsonkategoria.json", function(data){
var categories_data = '';
$.each(data, function(key, value){
categories_data += '<tr>';
categories_data += '<td><a href="' + value.link + '" >' + value.nazwa + '</a></td>';
categories_data += '</tr>';
});
$('#categories_tab').append(categories_data);
});
});
You misplaced anchor tag, it should be inside td not outside td
$(document).ready(function(){
$.getJSON("jsonkategoria.json", function(response){
$.each(response, function (i, value) {
$('<tr>').append(
$('<td>').append('<td><a href="' + value.link + '" >' + value.link + '</a></td>'),
$('<td>').text(value.nazwa).appendTo('#categories_tab');
});
});
});

Span Styles not Taking Effect

I have some content being added to a page via an AJAX call, and all of my styles are working, except one:
.bld-txt {
font-weight: bold;
}
The call itself looks like this:
$('#quick-search').submit(function(evt) {
evt.preventDefault();
$('.quick-search-info').empty();
var artistName = $(this).serialize();
$.post('/', artistName, function(data) {
var parsedInfo = $.parseJSON(data);
var tourDetails = '';
$.each(parsedInfo, function(i, val) {
tourDetails += '<li class="tour-date">';
tourDetails += '<ul class="show-details">';
tourDetails += '<li class="show-date"><span class="bld-txt">Date: </span>' + parsedInfo[i].formatted_datetime + '</li>';
tourDetails += '<li class="show-venue"><span class="bld-txt">Venue: </span>' + parsedInfo[i].venue.name + '</li>';
tourDetails += '<li class="show-location"><span class="bld-txt">Location: </span>' + parsedInfo[i].venue.city + ", " + parsedInfo[i].venue.region + '</li>';
tourDetails += '<li class="show-tickets"><span class="bld-txt">Tickets: </span>' + parsedInfo[i].ticket_status + '</li>';
tourDetails += '</ul>';
tourDetails += '</li>';
});
$('.quick-search-info').append(tourDetails);
});
});
All other classes that have styles assigned to them thus far are working, but for some reason "bld-txt" will not take effect.
I'm using a reset (normalize.css), but there's nothing in it that should be causing this.
Any guidance is greatly appreciated.

How to limit the results of codepen rss feed

I am working on my codepen rss feed for my website. I am having small issue limiting the results.
Currently displays over 10 results in the rss feed. But I would like to know the best way to limit results to 5
Question: How could I limit the results of my rss feed to 5 only.
Codepen Example
<script type="text/javascript">
$(document).ready(function(){
url = 'http://codepen.io/riwakawebsitedesigns/public/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(xml){
var postlist = xml.responseData.feed.entries;
var html = '<ul class="list-unstyled">';
$.each(postlist, function(idx, data) {
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
});
html += '</ul>';
$(".codepen_feed").append(html);
}
});
});
</script>
Use a return value for your each loop
$.each(postlist, function(idx, data) {
var title = data.title;
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
return idx < 4;
});

Why is my table being injected into the html multiple times with jQuery

I'm using Jquery to dynamically return a list of products, render this as HTML and then show it on the page, using $(selector).html(html).. however I've noticed if I add products to my cart too quickly (which calls the method to render the cart again, it is injecting the html twice sometimes.
For example, below code is what renders the menu:
html = " <table cellspacing=\"0\" width=\"270px\">\n";
html += " <tr>\n";
html += " <th>\n";
html += " <h1>\n";
html += " Current Order ID: " + $("input[name=cart_id]").val() + "\n";
html += " </h1>\n";
html += " </th>\n";
html += " </tr>\n";
html += " <tr id=\"cart_products\">\n";
html += " </tr>\n";
return $.ajax({
url: getAjaxUrl("cart/get_product"),
data: args,
type: 'get',
global : false,
success: function(data) {
if ( data.success ) {
//cart is empty
if ( data.data == "" ) {
html += " <td>\n";
html += " Your Cart is currently empty!\n\n";
html += " </td>\n";
} else if ( ("data" in data) ) {
html += " <td class=\"product\">\n\n";
html += " <table cellspacing=\"0\" width=\"100%\">\n\n";
html += " <tr>\n";
html += " <th>\n";
html += " Product\n\n";
html += " </th>\n";
html += " <th>\n";
html += " Qty\n\n";
html += " </th>\n";
html += " <th>\n";
html += " Action\n\n";
html += " </th>\n";
html += " </tr>\n";
//loop over all products in cart
$.each(data.data, function(i, product){
if ( i % 2 != 0 ) {
row_class = " alt";
} else {
row_class = "";
}
if ( ! product.ok ) {
row_class = " err";
}
//check if error
html += " <tr>\n";
html += " <td class=\"dsc" + row_class + "\">\n";
html += " <em>" + product.code + "</em><br />\n";
html += " " + product.description;
if ( product.whqc != "" )
html += " <br />WHQC: <strong>" + product.whqc + "</strong>\n";
else
html += " \n";
html += " </td>\n";
html += " <td class=\"qty + " + row_class + "\">\n";
html += " <input id=\"qty_" + product.id + "\" name=\"qty\" type=\"text\" value=\"" + product.qty + "\" class=\"qty\" maxlength=\"5\" size=\"5\" />\n";
html += " </td>\n";
html += " <td align=\"center\" class=\"action" + row_class + "\">\n";
html += " <img style=\"cursor:pointer; cursor:hand\" data-product_id=\"" + product.id + "\" id=\"cart_product_update\" src=\"" + getImageUrl() + "cart_product_update.png\" />\n";
html += " <img style=\"cursor:pointer; cursor:hand\" data-product_id=\"" + product.id + "\" id=\"cart_product_delete\" src=\"" + getImageUrl() + "cart_product_delete.png\" />\n";
html += " </td>\n";
html += " </tr>\n";
});
html += " </table>\n";
html += " </td>\n";
}
$("#cart_products").html(html);
} else {
alert("error");
}
}
});
Starting at the line where it says html += "<td class=\"product\">\n\n"; is sometimes pushed into the html twice.
Any idea why that is and how to stop it? I thought using html method was safe as it doesn't append- it replaces, however it seems that the method is stepping on its own toes. I know I could do something with boolean values like isLoading = true, however I'd like to avoid that.
You probably should initialize your html variable properly:
var html = '';

Categories

Resources