flickr api, json and set list - javascript

I am trying to build urls to thumbs of photsets, starting with the 'farm' value from the json feed. I cant see why this is not working..?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ajax_get_json(){
var menu = document.getElementById("menu");
var thumbURL = new XMLHttpRequest();
thumbURL.open("GET", "http://api.flickr.com/services/rest/?&method=flickr.photosets.getList&api_key=797507e576c902b2ffb0c8494fb368ab&user_id=37003559#N03&format=json&jsoncallback=?", true);
thumbURL.setRequestHeader("Content-type", "application/json", true);
thumbURL.onreadystatechange = function() {
if(thumbURL.readyState == 4 && thumbURL.status == 200) {
var data = JSON.parse(thumbURL.responseText);
menu.innerHTML = "";
for(var obj in data){
menu.innerHTML += data[obj].photosets.photoset.id+"<hr />";
}
}
}
thumbURL.send(null);
menu.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="menu"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
What did i miss..?

function ajax_get_json(){
var menu = document.getElementById("menu");
var thumbURL = new XMLHttpRequest();
thumbURL.open("GET", "https://api.flickr.com/services/rest/?&method=flickr.photosets.getList&api_key=797507e576c902b2ffb0c8494fb368ab&user_id=37003559#N03&format=json&jsoncallback=process", true);
thumbURL.onreadystatechange = function() {
if(thumbURL.readyState == 4 && thumbURL.status == 200) {
eval(thumbURL.responseText);
}
}
thumbURL.send(null);
menu.innerHTML = "requesting...";
}
function process(data) {
var menu = document.getElementById("menu");
menu.innerHTML = "";
var sets = data.photosets.photoset;
var max = sets.length;
for(var i = 0; i < max; i++) {
menu.innerHTML += sets[i].id+"<hr />"
}
}
http://jsfiddle.net/2BTrQ/10/

Related

How to open and makes query to sqlite database with JavaScript

I'm trying to do a client-side database visualizer with JS. I have never used JavaScript for doing this type of stuff, so I searched online and I found out this web page. This is the script that I have done.
<html>
<head>
<script>
function handleFiles(files)
{
var file = files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
openSqliteDb(reader);
}
function openSqliteDb(reader)
{
setTimeout(function () {
if(reader.readyState == reader.DONE)
{
var database = SQL.open(bin2Array(reader.result));
document.write("2");
executeQuery("SELECT * FROM User", database);
}
else
{
openSqliteDb(reader);
}
}, 500);
}
function executeQuery(commands, database)
{
document.write("1");
commands = commands.replace(/n/g, '; ');
try {
var data = database.exec(commands);
document.write(data);
processData(data);
} catch(e) {
console.log(e);
}
}
function processData(data)
{
document.write("1");
var colHeaders = [];
var colMap = {};
var tableContent = [];
var tableHtml = [];
tableHtml.push("<table border='1' cellspacing='2' cellpadding-'3'>");
for (var i = 0; i < data.length; i++) {
tableContent.push("<tr>");
var dataElem = data[i];
if (dataElem instanceof Array) {
for (var j = 0; j < dataElem.length; j++) {
var element = dataElem[j];
if (element.column && !colMap[element.column]) {
colHeaders.push("<th>" + element.column + "</th>");
colMap[element.column] = colHeaders.length;
tableContent.push("<td> " + element.value + "</td>");
} else {
tableContent.push("<td> " + element.value + "</td>");
}
}
} else {
if (element.column && !colMap[element.column]) {
colHeaders.push(element.column);
colMap[element.column] = colHeaders.length;
}
}
tableContent.push("</tr>");
}
tableHtml.push(colHeaders.join(" "));
tableHtml.push(tableContent.join(" "));
tableHtml.push("</table>");
document.getElementById("table").innerHTML = tableHtml.join(" ");
}
</script>
</head>
<body>
<input type="file" id="input" onchange="handleFiles(this.files)">
</body>
</html>
I can't figure it out why it is not working, but I think that the problem is the line var database = SQL.open(bin2Array(reader.result)); in the openSqliteDb() function. Can somebody help me?

How to dynamically load photos to dynamically loaded divs?

I wrote this code, which creates divs depending on the amount of text files in local directory.
Then I tried to write additional code, which appends photos to each of these divs. Unfortunately, this code doesn't append any photos...
function liGenerator() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var n = (xmlhttp.responseText.match(/txt/g) || []).length;
for (var i = 1; i < n; i++) {
$.get("projects/txt/"+i+".txt", function(data) {
var line = data.split('\n');
var num = line[0]-"\n";
var clss = line[1];
var title = line[2];
var price = line[3];
var content = line[4];
$("#list-portfolio").append("<li class='item "+clss+" show' onclick='productSelection('"+num+"')'><img src='projects/src/"+num+"/title.jpg'/><div class='title'><h1>"+title+"</h1><h2>"+price+"</h2></div><article>"+content+"</article></li>");
$("#full-size-articles").append("<li class='product "+num+"'><div><div class='photo_gallery'><div id='fsa_img "+num+"'><div width='100%' class='firstgalleryitem'></div></div></div><article class='content'><h1 class='header_article'>"+title+"</h1><h2 class='price_article'>"+price+"</h2><section class='section_article'>"+content+"</section></article></div></li>");
});
}
}
}
};
xmlhttp.open("GET", "projects/txt/", true);
xmlhttp.send();
}
function pushPhotos() {
var list = document.getElementById("full-size-articles").getElementsByTagName("li");
var amount = list.length;
for(var i=1;i<=amount;i++) {
var divID = "#fsa_img "+i;
var where = "projects/src/"+i+"/";
var fx = ".jpg";
loadPhotos(where, fx, divID);
}
}
function loadPhotos(dir, fileextension, div) {
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location, "").replace("http://", "");
$(div).append("<img src='"+dir+filename+"' class='mini_photo'/>");
});
}
});
}
Any ideas on why this code is not working as intended?
The main issue is the space between "#fsa_img" and "i". When I changed it to '"#fsa_img_"+i', the code started work as intended.

How to get website to load without clicking on the header

As of now I have to click on google to load google. Is there a way to just automatically load google without clicking on the title. I have tried removing the title and it will say unidentified and I click on that it will take me too google.
<html>
<body>
<div id="id01"></div>
<script>
var myArray = [
{
"display": "google",
"url":"https://google.com
},
]
myFunction(myArray);
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '' + arr[i].display + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>

JSON response returning null array

Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)
The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();

Submit the form when on browser reload/add new tab

Just got some codes from worldofwebcraft.com for my project examination system.I only know PHP,and I actually have no idea on javascripts because our teacher hasnt taught us yet. Please help me on how do I submit the form automatically when the user reloads the page or when he/she opens a new tab.
heres the codes:
<?php if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1; ?>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted.");
var url = 'exam.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
document.onkeydown = function() {
if(event.keyCode == 116) {
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
</script>
I would do something like :
window.onbeforeunload = function() {
post_answer();
}
If post_answer() is your "submit the form"-handler. Cannot tell exactly from the code.

Categories

Resources