I'm trying to get each hexadecimal value from the Adobe Kuler API using JQ/JS:
kuler api xml
They provide an xml but I'm having a hard time grabbing the values and placing them in an array like this:
var colors = [E6E2AF, A7A37E, EFECCA, 046380, 002F2F];
The colors exist in this element
<description>
Hex: E6E2AF, A7A37E, EFECCA, 046380, 002F2F
</description>
and here too:
<kuler:swatchHexColor>
E6E2AF
</kuler:swatchHexColor>
If you have any ideas I would really appreciate it,
K
I spent some time to find a selector that works for namespaces. This selector seems to do the job. Credits goes to Fasani for his answer in jQuery - XML parsing with namespaces.
$(xml).find('kuler\\:swatchHexColor, \\swatchHexColor');
Full snippet:
var colors = [];
$.ajax({
type: "GET",
url: 'https://kuler-api.adobe.com/rss/get.cfm?listType=popular&itemsPerPage=5&key=mykey',
dataType: "xml",
success: function(data){
// Select all <kuler:swatchHexColor> tags
var colorHexs = $(data).find('kuler\\:swatchHexColor, \\swatchHexColor');
// Loop through them, push them to colors array, and then append it body
$(colorHexs).each(function(i, hex){
colors.push($(hex).text()); // push to array
$('body').append('<div class="color" style="background:#'+$(hex).text()+'">'+$(hex).text()+'</div>');
});
// colors output.
console.log(colors);
}
});
.color {
width:33.334%;
height:100px;
float:left;
text-align:center;
line-height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Credits:
Fasani - jQuery XML parsing with namespaces
Related
I use ajax to render output to below HTML element.
<p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p>
Everything works fine when rendering result for the 1st input request.
When I update my input, the console changes and prints desired data but the webpage including the text does not change.
I get Cannot read property 'setAttribute' of null at canvas_and_ploton the 2nd+ time refresh below, If I remove setAttribute, I get Cannot read property 'getAttribute' of null at canvas_and_plot.
$(document).on('submit','#cat_select',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/cat_select',
data:{
l2:$('#l2').val(),
l3:$('#l3').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
const r = JSON.parse(response);
console.log(r); //updated
var cat_result = r.cat_result;
console.log(cat_result[0]) //updated
var text=$('<i></i>');
$.each(cat_result, function(idx, value) {
text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '<br>'); //even the text output are not updated
text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas><br>');
});
$('#result').replaceWith(text);
$.each(cat_result, function(idx, value) {
canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])});
}
function canvas_and_plot(idx,a,b,c) {
var canv = document.getElementById('canv_'+idx);
canv.setAttribute('id', 'canv_'+idx);
var C = document.getElementById(canv.getAttribute('id'));
//plot...
}
I tried adding cache: false and adding random number to the url but neither of them works.
Why only error after the first request? How can I fix this? Thanks
The reason for it not changing is that you are replacing your block #result with received data.
$('#result').replaceWith(text);
After which you'll a dom tree that looks something like this:
<p class="result-box" id="result-box">
The result is : <br>
<i>
<id="result123">...<br>
<canvas id="canv123" width="200" height="200"></canvas><br>
<id="result321">...<br>
<canvas id="canv321" width="200" height="200"></canvas><br>
</i>
</p>
So the second time you click there is no element with #result id.
I suggest (as a rough and quick solution):
On every request remove all children of your #result element and fill it again with new data. So add this line before making the request - $('#result').empty(); and replace $('#result').replaceWith(text); with $('#result').append(text);
The main idea is to keep the place you put and add your server data. Hope this helps!
I made a small webpage that asks the user to enter the name of an actor and I was hoping to then display all of the movies the actor had appeared in. For my question, I've hard coded the api URL for the actor (Bradley Cooper).
How do I grab all of the movie titles, the release year, movie overview, and the movie poster value and display them all on the page? Right now, I'm only able to display one movie and for some strange reason, it's not the first movie mentioned in the json file.
I think I need to get the json data into an array but I'm not sure how to do that and I'm not sure how to then display more than one result on the page.
I appreciate any help and guidance you can provide.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="search_actor()">
<script>
function search_actor() {
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.cast).each(function(index, moviedata) {
// Movie Title
document.getElementById("movietitle").innerHTML = moviedata.title;
// Release Year
document.getElementById("releaseyear").innerHTML = moviedata.release_date.substr(0, 4);
// Movie Overview
document.getElementById("movieoverview").innerHTML = moviedata.overview;
// Movie Poster
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
document.getElementById("displaymovieposter").innerHTML = fullmovieposterpath;
});
}
});
}
</script>
<div id="movietitle"></div>
<div id="releaseyear"></div>
<div id="movieoverview"></div>
<div id="displaymovieposter"></div>
</body>
</html>
In your code you have single only one container to display the movie items.You need to loop over the response and dynamically create the movie cards.Also use css grid system to have more control over the movie card and their placement.
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
console.log(data)
let k = '';
data.cast.forEach(function (item) {
//Using template literal to create a movie card
k += `<div class='movie-card'>
<div>${item.original_title}</div>
<div><img src = 'https://image.tmdb.org/t/p/w500/${item.poster_path}'></div>
<div><span>${item.release_date}</span></div>
<div class='movie-desc'>${item.overview}</div>
</div>`
})
$('.movie-conatiner').append(k)
}
});
See complete working copy here at stackblitz
Currently, you are displaying data in single division, so data is getting overwritten.
Instead you need to dynamically build division in for each statement and then assign the entire data in home page.
Also create only single div in html part with id="main"
Below is the updated code with above change. Please give proper CSS to the divisions.
Code after getting json response
divcnt=1;
divdata="";
$(data.cast).each(function(index, moviedata) {
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
divdata += '<div id="test'+ divcnt +'"><div id="movietitle'+ divcnt +'">'+moviedata.title+'</div><div id="releaseyear'+ divcnt +'">'+moviedata.release_date.substr(0, 4)+'</div><div id="movieoverview'+ divcnt +'">'+moviedata.overview+'</div><div id="displaymovieposter'+ divcnt +'">'+fullmovieposterpath+'</div></div>';
});
document.getElementById("main").innerHTML = divdata;
recently I reached out on here for some help regarding javascript. I needed something that parsed a CSV file and outputted it to HTML.
Someone was able to help me massively. only problem is that it outputs as a one row table. In the CSV file each row does not have a specific amount of columns/data meaning that the row data varies in length.
what I've been trying to do is write some if statements to only pick up things like 'Last name' or 'known for' so i can give some order to the results.
What is the best way to do this? I will need to style the output data so i'm thinking div id's would be better than tables. also, where abouts in the code should i edit (my javascript knowledge is very beginner).
if statement i tried (probably totally wrong):
function firstName($container){
var firstN = $container;
var n = firstN.includes("First Name");
if (n != 0){
document.getElementById("first_name").innerHTML="First name = ";
return;
}
}
main block of code (CSV file can be found at http://www.fooda.website/testResults.csv):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.12.3.min.js" type="text/javascript">
</script>
<title>Untitled Document</title>
<script type="text/javascript">
// ============================
// Allow for a cached result
// ============================
var csvRows = [];
// ============================
// ============================
// Given an array of rows build a table.
// ============================
function buildTable(csvRows){
// Our base result
var $table = $("<table cellpadding=\"2\" cellspacing=\"0\"></table>");
// ============================
// For each row in the CSV build a <tr /> and append it to the <table />
// ============================
$table = csvRows.reduce(function($table, csvRow){
// For this demo just take the first few cells/columns
var csvRowCells = csvRow.split(",");
// Our base table row
var $tr = $("<tr>/tr>");
// ============================
// For each cell row build a <td /> and append it to the <tr />
// ============================
$tr = csvRowCells.reduce(function($tr, csvRowCell){
return $tr.append($("<td>/</td>").text(csvRowCell));
}, $tr);
// ============================
// Add our new <tr /> to the table then return the table
return $table.append($tr);
}, $table);
// ============================
return $table;
}
// ============================
// ============================
// Given an array of rows, randomly select one (as an array) and build a table with it.
// ============================
function fillContainerWithTable(csvRows, $container){
var randomRow = [csvRows[Math.floor(Math.random() * csvRows.length)]];
var $table = buildTable(randomRow);
$container.append($table);
}
// ============================
// ============================
// the click handler
// ============================
function myFunction(){
// some random csv I found...
var uri = "http://www.fooda.website/testResults.csv";
var $container = $("#wrap");
// You probably want a clean slate.
$container.empty();
// ============================
// If we have the data locally already just use it.
// ============================
if (csvRows.length !== 0){
console.log("using local data...");
fillContainerWithTable(csvRows, $container);
return;
}
// ============================
console.log("fetching remote data...");
$.get(uri, function(data){
csvRows = data.split("\n");
fillContainerWithTable(csvRows, $container);
});
}
// ============================
</script>
<style type="text/css">
body {
font-family: arial, helvetica, sans-serif;
font-weight: normal;
font-size: 13px;
color: #000;
text-align: left;
margin: 3px 0px;
}
#wrap {
padding: 20px;
}
#wrap table {
border: solid 1px;
border-collapse: collapse;
background-color: aliceblue;
height:400px;
width:100%;
}
#first_name {
height:200px;
width:200px;
background-color:#0C0;
}
</style>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<div id="wrap"></div>
<div id="first_name">
</div><!--first_name-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Thanks in advance!
Short answer is "this is a duplicate of the many 'how do I convert JSON into an HTML table' questions on SO" and in the end I'm just going to point you towards some of them, but I want to walk you through it.
CVS (comma-separated values) looks like
Col1,Col2,Col3,Col4
row1value1,row1value2,row1value3
row2value1,row2value2
row3value1,,row3value3,row3value4
While not necessarily the case, you can think of CSV as a very compact way text-only of writing a table, where each row's values are in the same order (like table columns) and empty cells look like ",,". If the above csv was a table (e.g. if you imported it into Excel etc), it would be
Col1 Col2 Col3 Col4
row1value1 row1value2 row1value3
row2value1 row2value2
row3value1 row3value3 row3value4
Your data, on the other hand, is actually a list of JSON "objects", one per line. In JSON, an object is contained within { } and is made up of "key/value" pairs. A JSON object looks like
{"key1":"value1", "key2":"value2"}
JSON lets you group objects into arrays. A JSON array is contained within [ ].
In JSON, the above table would look like
[{'Col1':'row1value1','Col2':'row1value2','Col3':'row1value3'},
{'Col1':'row1value1','Col2':'row1value2'},
{'Col1':'row1value1','Col3':'row1value3','Col4':'row1value4'}]
When working with JSON, you can say "loop through each object in an array" and "for the current object, give me the Col2 value." (Note this means related JSON objects don't have to list the key/value pairs in the same order, and you don't have to specify missing values.) If you knew every possible key in your array (in this case, that'd be Col1, Col2, Col3, and Col4) you could say
"Loop through the array, put each object in a <tr>, and for each
object first put the Col1 value in a <td>, then put the Col2 value
in a <td>, then put the Col3 value in a <td>, then put the Col4
value in a <td>."
That's exactly what you want to do… and it turns out there are already a bunch of tools out there to do it! The only thing standing between you and using them is putting a [ at the start of your file, a , at the end of every line except the last, and a ] at the end of the file. If you can do this, you're in luck. If this is static data, just open the data up in a text editor and use a find/replace to add in the end-of-line commas. If it's being generated on the fly, you'll have to come up with a way to add things (the solution will be something like tack on [, split the file by }, tack on each chunk of the split data followed by a , unless it's the last chunk, then tack on a ], and then run that through a JSON-to-HTML-table tool). I'll leave how exactly to do that up to you -- if you get stumped, definitely open up a new "how can I convert a list of json objects into a json array" question. I'm not a JSON expert, and I bet there's some standard way of doing it
Here are a couple promising JSON-to-HTML-table solutions. I'll be interested to hear if one of them works for you!
Convert json data to a html table
Parsing JSON objects for HTML table
Convert JSON array to an HTML table in jQuery
https://github.com/afshinm/Json-to-HTML-Table
I'm trying to read from xml file text and remove nodes where that text was.
For example I read the text from <en> or <es> nodes and I need to remove those both nodes and save text to <translation>
xml file before editing:
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<name>
<translation>
<en>
Text 1
</en>
<es>
Text 2
</es>
</translation>
</name>
</books>
So it should looks like this:
<books>
<translation>
Text 1
</translation>
</books>
this is part of my function where after reading text from <en> I'm trying to remove all child nodes from <translation> but I'm stuck and getting an error when I'm using removeChild method
var lang = 'en';
$.ajax({
type: "GET",
url: 'my.xml',
dataType: "xml",
success: function (xml) {
$(xml).find('translation').each(function () {
var text = $(this).find(lang).text();
});
$(xml).getElementsByTagName('translation').parentNode.removeChild();
// xml convert to json
var books = [];
var data = $.xml2json(xml)['#document'];
that.books = data.books;
}
});
I'll appreciate any help. Thank you!
var value = [];
$.get("your.xml", function(d){
values.push($(d).find("en")[0].childNodes[0]); //push "Text 1" into array
$(d).find("en").remove(); //remove node
$(d).find("es").remove(); //remove node
$(d).find("translation").append(values[0]); //add "Text 1" to node
});
The problem you're running into is that you're attempting to use a jQuery object as a DOM node here:
$(xml).getElementsByTagName('translation').parentNode.removeChild();
To use jQuery, you would do
$(xml).find('translation').remove();
HOWEVER, I think you're possibly headed down a false path. I see you've declared a var text that isn't used anywhere in your code. You probably want to do something like the following:
$xml = $(xml);
$xml.find('translation').each(function () {
$this = $(this);
$this.text($this.find(lang).text());
});
// do something with $xml...
I couldn't get xml2json working, as I'm not familiar with that plugin, but it should be relatively straightforward for you.
tried this?
getElementsByTagName('translation').children().remove()
im trying to implement mention using (#) on a textarea that feeds from MySQL database.
this is the code im using below
var start=/#/ig; // # Match
var word=/#(\w+)/ig; //#abc Match
$("#newstatus").live("keyup",function()
{
var content=$(this).val() //Content Box Data
var go= content.match(word); //Content Matching #
var name= content.match(word); //Content Matching #abc
var dataString = 'searchword='+ name;
//If # available
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
//if #abc avalable
if(name.length>0)
{
$.ajax({
type: "POST",
url: siteurl + "ajax/mention", // Database name search
data: dataString,
cache: false,
success: function(data)
{
$("#msgbox").hide();
$("#display").html(data).show();
}
});
}
}
return false;
});
The problem happens when i add more text it keeps showing suggested box, i want to stop searching whenever i start a new sentence after the #WORD im using e.g.
#blackberry is my favorite smartphone !
i may use more than one mention in that textarea !
i want your help how do i do that whenever i use # then i have suggested list whenever i choose i can continue writing and may use another mention
Solution is:
$("#newstatus").live("keyup",function()
{
var content=$(this).val() //Content Box Data
var index= content.lastIndexOf("#"); //Content Matching #
var name= content.substr(n+1);; //Content Matching abc, If you want to get #abc then remove +1.
var dataString = 'searchword='+ name;
Explanation:
I am searching last position of # in a given string (using lastIndexOf()) and from that I am getting the string till end using substr().
You no need to use reg exp for this. Regular Exp are very costly, it will consume more resources, According to my knowledge better to ignore regular exp for a small operations.