Itunes API Use With JQuery - javascript

I am using the code below which i found on: http://www.rahulsingla.com/blog/2011/08/itunes-performing-itunes-store-search-in-javascript to pull songs from Itunes based on a keyword, however i only want to pull songs on page-load without having to use the search box, lets say my keyword is "search-keyword", i would like to display songs immidiately on page-load or refresh without using the search box, here is the code below:
<html>
<head>
<title>iTunes - Music Search in javascript</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<style type="text/css">
.songs-search-result {
border: 1px solid Gray;
margin-bottom: 5px;
padding: 5px;
}
.songs-search-result .label{
display: inline-block;
width: 200px;
}
</style>
<script type="text/javascript">
function urlEncode(obj) {
var s = '';
for (var key in obj) {
s += encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]) + '&';
}
if (s.length > 0) {
s = s.substr(0, s.length - 1);
}
return (s);
}
function performSearch() {
var params = {
term: encodeURIComponent(jQuery('#search-keyword').val()),
country: 'US',
media: 'music',
entity: 'musicTrack',
//attribute: 'artistTerm,albumTerm,songTerm,musicTrackTerm',
limit: 20,
callback: 'handleTunesSearchResults'
};
var params = urlEncode(params);
var url = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?' + params;
var html = '<script src="' + url + '"><\/script>';
jQuery('head').append(html);
}
function handleTunesSearchResults(arg) {
var results = arg.results;
var html = '';
for (var i = 0; i < results.length; i++) {
var item = results[i];
var obj = {
source: 0,
track_id: item.trackId,
track_name: item.trackCensoredName,
track_url: item.trackViewUrl,
artist_name: item.artistName,
artist_url: item.artistViewUrl,
collection_name: item.collectionCensoredName,
collection_url: item.collectionViewUrl,
genre: item.primaryGenreName
};
results[i] = obj;
html += '<div class="songs-search-result">';
html += '<span class="label">Track:</span>{0} '.replace("{0}", obj.track_name);
html += 'Preview '.replace("{0}", item.previewUrl);
html += 'Full Song '.replace("{0}", obj.track_url);
html += '<span class="label">Track Price:</span>{0} {1}<br />'.replace("{0}", item.trackPrice).replace("{1}", item.currency);
html += '<span class="label">Artist:</span>{1}<br />'.replace("{0}", obj.artist_url).replace("{1}", obj.artist_name);
html += '<span class="label">Collection:</span>{1}<br />'.replace("{0}", obj.collection_url).replace("{1}", obj.collection_name);
html += '<span class="label">Collection Price:</span>{0} {1}<br />'.replace("{0}", item.collectionPrice).replace("{1}", item.currency);
html += '<span class="label">Primary Genre:</span>{0}<br />'.replace("{0}", obj.genre);
html += '</div>';
}
jQuery('#itunes-results').html(html);
}
</script>
</head>
<body>
Please enter a search term below (e.g. Michael):<br />
<input type="text" id="search-keyword" title="Enter Search Keyword" />
<br />
<input type="button" value="Perform iTunes Search" onclick="performSearch();" />
<div id="itunes-results">
</div>
</body>
</html>

Related

javascript : to update all <td> element of <tr> in textbox when click on edit

I am new to working in javascript, I am work Dom element and create a demo of crud with the table.
CRUDCODE:
<html>
<head>
<style type="text/css">
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>
<input type="text" id="name"><br /><br />
<input type="text" id="age"><br /><br />
<input type="text" id="email"><br /><br />
<input type="button" value="addNew" id="addNew"><br />
<div id="output"></div>
<script>
let rows = [{
name: "John",
age: 20,
email: "abc#gmail.com"
}, {
name: "Jack",
age: 50,
email: "pqr#gmail.com"
}, {
name: "Son",
age: 45,
email: "xyz#gmail.com"
}];
window.onload = building();
let addNew = document.getElementById("addNew");
addNew.onclick = function () {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let email = document.getElementById("email").value;
rows.push({
name,
age,
email
});
console.log(rows);
building();
}
function building() {
let html = "<h1>student-Info</h1><table align='center'>";
for (let i = 0; i < rows.length; i++) {
html += '<tr id="id' + i + '"data-row="' + i + '">';
html += "<td>" + rows[i].name + "</td>";
html += "<td>" + rows[i].age + "</td>";
html += "<td>" + rows[i].email + "</td>";
html += "<td><a href='#' data-action='delete'>DELETE</a></td>";
html += "<td><a href='#' data-action='edit'>Edit</a></td>";
html += '</tr>';
}
html += "</table>";
document.querySelector('#output').innerHTML = html;
let deleted = document.querySelectorAll('[data-action="delete"]');
for (let i = 0; i < deleted.length; i++) {
deleted[i].addEventListener('click', function () {
event.preventDefault();
let ival = this.closest('[data-row]').getAttribute('data-row');
let r = rows.splice(ival, 1);
building();
console.log(r);
})
}
let edited = document.querySelectorAll('[data-action="edit"]');
console.log(edited);
for (let i = 0; i < edited.length; i++) {
edited[i].addEventListener('click', function () {
event.preventDefault();
let row = this.closest('[data-row]');
let rid = row.getAttribute('data-row');
let td = row.firstElementChild;
let input = document.createElement("input");
input.type = "text";
input.value = td.innerText;
td.innerHTML = "";
td.appendChild(input);
input.onblur = function () {
td.removeChild(input);
td.innerHTML = input.value;
rows[rid] = input.value;
}
})
}
}
</script>
</html>
I am getting all array data in loop "table" but when I click on edit I am not able to convert all "td" element
in "input" field,only first ""
the element will be converted.
Anybody have any idea please help to sort it out. Thanks
You apply the input field for firstElement in your code, but you need to get all the editable table field and update it like this
<html>
<head>
<style type="text/css">
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>
<input type="text" id="name"><br /><br />
<input type="text" id="age"><br /><br />
<input type="text" id="email"><br /><br />
<input type="button" value="addNew" id="addNew"><br />
<div id="output"></div>
<script>
let rows = [{
name: "John",
age: 20,
email: "abc#gmail.com"
}, {
name: "Jack",
age: 50,
email: "pqr#gmail.com"
}, {
name: "Son",
age: 45,
email: "xyz#gmail.com"
}];
window.onload = building();
let addNew = document.getElementById("addNew");
addNew.onclick = function () {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let email = document.getElementById("email").value;
rows.push({
name,
age,
email
});
building();
}
function building() {
let html = "<h1>student-Info</h1><table align='center'>";
for (let i = 0; i < rows.length; i++) {
html += '<tr id="id' + i + '"data-row="' + i + '">';
html += "<td data-col='name'>" + rows[i].name + "</td>";
html += "<td data-col='age'>" + rows[i].age + "</td>";
html += "<td data-col='email'>" + rows[i].email + "</td>";
html += "<td><a href='#' data-action='edit'>Edit</a></td>";
html += "<td><a href='#' data-action='delete'>DELETE</a></td>";
html += '</tr>';
}
html += "</table>";
document.querySelector('#output').innerHTML = html;
let deleted = document.querySelectorAll('[data-action="delete"]');
for (let i = 0; i < deleted.length; i++) {
deleted[i].addEventListener('click', function () {
event.preventDefault();
this.closest('[data-row]').parentNode.removeChild(this.closest('[data-row]'));
})
}
let edited = document.querySelectorAll('[data-action="edit"]');
for (let i = 0; i < edited.length; i++) {
edited[i].addEventListener('click', function () {
event.preventDefault();
let row = this.closest('[data-row]');
let rid = row.getAttribute('data-row');
const tdList = row.querySelectorAll('td[data-col]');
[...tdList].forEach(td => {
let input = document.createElement("input");
input.type = "text";
input.value = td.innerText;
td.innerHTML = "";
td.appendChild(input);
input.onblur = function () {
td.removeChild(input);
td.innerHTML = input.value;
rows[rid][td.dataset.col] = input.value;
}
})
})
}
}
</script>
</html>

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

javascript json class onclick hide another json class

I don't understand why it is important to view or see when its just the logic I'm looking for.. However I just added the index.html file that can make things show... I hope it helps anyone !
what I'm trying to achieve is..
var small = document.getElementsByClassName("small");
var story = document.getElementsByClassName("story");
small.onclick = function() { story.style.display = "block"; }
I'm aware they should be done for loop and added as [i] in the end of both vars...
But how can i relate each small to story when they're both same id...
How can I tell
document.getElementsByClassName("small")[0];
to show
document.getElementsByClassName("story")[0];
when I have Multiple Class Values...
Thought about adding (this) in onclick() html tag but im not experienced enough....
Here's the Main Code:
var div = document.getElementById("content");
var ajax = new XMLHttpRequest();
ajax.open('GET', 'rss.json', true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4 && ajax.status == 200)
{
var items = JSON.parse(ajax.responseText);
var output = '<ul class="main">';
for(var key in items)
{
output += '<li class="IDZ"><b><pre>' + items[key].IDZ + '</b></pre></li>';
output += '<li class="topic"><h1><u>' + items[key].topic + '</u></h1></li>';
output += '<li id="" class="small"><a href="#" >' + items[key].small + '</a></li><br>';
output += '<li class="story">' + items[key].story + '</li><br>';
output += '<li class="media"><img src='+items[key].media+'>' + '</li>';
output += '<hr>';
}
output += '</ul>';
div.innerHTML = output;
}
}
ajax.send(null);
rss.json file
{
"rss1":
{
"IDZ" : 1,
"topic" : "Topic One",
"small" : "A Brief Intro about this story.",
"story" : "Main Story starts when A B C were born to become all good and tidy for the little things that made IDZ : 1 A Story",
"media" : "images/IDZ1.jpg"
},
"rss2":
{
"IDZ" : 2,
"topic" : "Topic 2",
"small" : "A Brief Intro about another story.",
"story" : "Main Story starts when A B C were born to become all good and tidy for the little things that made IDZ : 2 A Story",
"media" : "images/IDZ2.jpg"
}
}
<!DOCTYPE html>
<html encoding="utf-8" >
<head>
<title>json parser</title>
<style>
/* { border: 0; margin:0; padding: 0;} */
body { position: relative; }
ul { }
li { list-style-type: none; font-size:1em;}
a { text-decoration: none; }
a:visited { color: #f22; }
.id { text-align: center; }
</style>
<script>
document.onreadystatechange = function()
{
if(document.readyState == "complete")
{
var loadscript = document.getElementById("content");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "script.js";
loadscript.appendChild(script);
}
}
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>
You could use the "data" attribute to store the key and also include the key in the id as follows:
for(var key in items)
{
output += '<li id="" data-key="'+ key +'" class="small"><a href="#" >' + items[key].small + '</a></li><br>';
output += '<li class="story" id="story_key_'+ key +'">' + items[key].story + '</li><br>';
}
small.onclick = function(elem)
{
story.style.display = "block";
var storyKey = elem.dataset.key;
var storyItem = document.getElementById("story_key_" + storyKey);
}
(Note: this is only an idea, this code isn't working code)

Search mechanism is not working in Html Table

Im working on search mechanism in html, it is working when i search the data at first time. if i search for next data, it wont search as expected. If i search with empty data, it wont display actual table(which displayed at initial time).
JsFiddle : http://jsfiddle.net/DHJ79/
Even any better pointer is also welcome, if my below code is not good.
My code:
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<style> td{border: thin solid;} </style>
<script type="text/javascript">
function searchTable(inputVal) {
var inputVal = document.getElementById('searchdata').value;
$('.table').html($('.table').html().replace(RegExp(inputVal, 'g'), '<span class="showthis">' + inputVal + '<span>'));
$("tr").css('display', 'none');
$(".showthis").parent().parent().css('display', '');
}
function addList(){
var table = "";
table += "<table class='table'>";
table += "<tr>";
table += "<td>S.no</td>";
table += "<td>Name</td>";
table += "<td>Gender</td>";
table += "</tr>";
for(i=0; i<10; i++) {
table += "<tr>";
table += "<td>"+i+"</td>";
table += "<td>Name"+i+"</td>";
table += "<td>"+( i > 5 ? "Male" : "Female")+"</td>";
table += "</tr>";
}
table += "</table>";
var body = document.getElementById("ListContainer");
body.innerHTML = table;
}
</script>
</head>
<body onload="addList();">
<input id="Button1" type="button" value="button" onclick="searchTable();" />
<input id="searchdata" type="text" />
<div id="ListContainer" > </div>
</body>
</html>
Advance thanks...
Maybe something like this.
function searchTable(inputVal) {
var inputVal = document.getElementById('searchdata').value;
if (inputVal == "") {
$('.hideThis').removeClass('hideThis');
} else {
$('tr').addClass('hideThis');
$('tr:has(td:contains(' + inputVal + '))').removeClass('hideThis');
}
}
modify your search function as follows:
function searchTable(inputVal) {
var inputVal = document.getElementById('searchdata').value;
if(inputVal){ //check for valid searches
//addList();
$('.table').html($('.table').html().replace(RegExp(inputVal, 'g'), '<span class="showthis">' + inputVal + '<span>'));
$("tr").css('display', 'none');
$(".showthis").parent().parent().css('display', '');
}
else{
addList(); // if you don't want to reinitialize table on empty searches skip this
}
}

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!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">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Categories