JSON and jQuery - javascript

I have this thing working mostly. What I don't get is, if I have the file on my desktop and drag it into a browser, it works. If I upload the same file to my website and visit it, it displays nothing in Firefox. Last night it worked in Safari, but today it does not. Is something really weird in this code?
Here is the pastie in case pasting all this in here does not work :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{
background: #353535;
color: #fff;
font-size: 62.5%;
padding: 10px;
}
p{
font-size: 1.6em;
font-family: Arial, "MS Trebuchet", sans-serif;
}
span{
font-size: 1.6em;
font-variant: small-caps;
}
ul {
list-style: none;
}
li {
font-size: 1.6em;
text-transform: capitalize;
}
img{
float: left;
margin: 10px;
}
</style>
<!-- actual api http://api.tinychat.com/designtalk.json -->
<!-- testing file test.json -->
<script>
$(document).ready(function(){
$.getJSON("http://api.tinychat.com/designtalk.json",
function(data){
$('#name').append(data.name);
$('#topic').append(data.topic);
$('#broadcast').append(data.broadcaster_count);
$('#count').append(data.total_count);
$('#priv').append(data.priv);
if(!data.name)
{
alert("Room empty!")
}
var $nameList = $('<ul></ul>');
$.each(data.names, function (i, val) {
$('<li></li>').appendTo($nameList).html(val);
});
$('#container').append($nameList);
$.each(data.pics, function (i, val) {
$("<img/>").attr("src", val).appendTo("#images");
});
});
});
</script>
</head>
<body>
<p id="name"><span>Room Name:</span> </p>
<p id="topic"><span>Current Topic:</span> </p>
<p id="broadcast"><span>Number Broadcasting:</span> </p>
<p id="count"><span>Total in Room:</span> </p>
<p id="priv"><span>Number with Privileges:</span> </p>
<div id="container"><span>Who is Online?</span></div>
<div id="images"></div>
</body>
</html>

In the callback function you would just go through each element. Let's say you wanted to append the names to a div with the id of namesDiv you might do this:
$.get("something.aspx", function(json) {
for(var i =0; i< json.names.length; i++)
{
$('#namesDiv').append(json.names[i]);
}

You can create HTML elements programmatically, to build an HTML List for example:
$('<div></div>').appendTo('#container').html(data.title);
var $nameList = $('<ul></ul>');
$.each(data.names, function (i, val) {
$('<li></li>').appendTo($nameList).html(val);
});
$('#container').append($nameList);
Example here.
Without jQuery:
var container = document.getElementById('container'),
title = document.createElement('div'),
nameList = document.createElement('ul'), li;
title.innerHTML = data.title;
for (var i = 0; i < data.names.length; i++) {
li = document.createElement('li');
li.innerHTML = data.names[i];
nameList.appendChild(li);
}
container.appendChild(title);
container.appendChild(nameList);
Example here.
Edit: In response to your comment, you were missing the Flickr specific parameter jsoncallback to make the JSONP request, and also in the structure of the JSON response the names member doesn't exists, I think you mean items.
Check your feed example fixed here.

There is a firefox plugin which formats json data. https://addons.mozilla.org/en-US/firefox/addon/10869
This is assuming you only want to learn what the json data looks like and hence start programming in it...

Very long in the tooth, but it does take care to recognize that properties of your object may have their own properties as well. Assumes a DIV element (or similar) exists with an ID of "content."
function WriteObject(obj, tabs)
{
tabs = tabs || 0;
var padding = "";
for(var i = 0; i < tabs; ++i)
{
padding += "\ ";
}
for(var prop in obj)
{
if(typeof(obj[prop]) === "object")
{
if(obj[prop].constructor === Array)
{
var str = obj[prop].join(",");
$("#content").append(padding + prop + ": " + str + "<br />");
}
else
{
$("#content").append(padding + prop + "<br />");
WriteObject(obj[prop], tabs + 1);
}
}
else
{
$("#content").append(padding + prop + ": " + (obj[prop] ? obj[prop] : "null") + "<br />");
}
}
}

You can try the page below:
In modern browsers you don't need anymore the json2.js library from json.org
<html>
<head>
<script src="http://www.json.org/json2.js"></script>
</head>
<body>
<pre id="res"></pre>
<script>
var json = {
"title":"No title",
"names":["", "dave", "jeff", "sean", "", ""],
"total_people":3
};
document.getElementById('res').innerHTML = JSON.stringify(json, null, 2);
</script>
</body>
</html>

Related

replace text from string not working javascript

i cant seem to get this code to work i’ve been trying at it for hours i'm trying to make a formatting system for html markup and later js and css once i can get this working the desired outcome here to to have a list of items in the var l string detect in the contenteditable <p>tag but cant get it to give me any outcome same issue when applying a filter to replace words in a string with </tag> i'm not sure if this is a syntax issue or just something i'm missing but i cant for the life of me find the error in my code any help is appreciated
<html>
<style>
.form {
color: green;
background: black;
}
</style>
<body>
<button onclick="register()">format</button>
<p id="demo" contenteditable>tags to format- <head> <body> <html> <span></p>
<script>
function register() {
let text = document.getElementById("demo").innerHTML;
var l = ["head","body","html","span"];
for(let i = 0; i < l.length; i++) {
setTimeout(function() {
document.getElementById("demo").innerHTML =
text.replace("<"+ l[i] +">","<span class='form'><"+ l[i] +"></span>");
},500);
}
}
</script>
</body>
</html>
You were overriding the innerHTML each time. Only change the innerHTML once.
function register() {
let text = document.getElementById("demo").innerHTML;
var l = ["head","body","html","span"];
for(let i = 0; i < l.length; i++) {
text =
text.replace("<"+ l[i] +">","<span class='form'><"+ l[i] +"></span>");
}
document.getElementById("demo").innerHTML = text;
}
.form {
color: green;
background: black;
}
<button onclick="register()">format</button>
<p id="demo" contenteditable>tags to format- <head> <body> <html> <span></p>

Why do I lose formatting after running javascript?

This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle

How to add URLs to the bookmarks?

I want to add any URL of CurrentTabs here in this "popup.js" to bookmarks.
function GetUrls()
{
var CurrentTabs = new Array();
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++)
{
CurrentTabs[i] = tabs[i];
}
for (var i = 0; i < CurrentTabs.length; i++)
{
document.write("<b>" + CurrentTabs[i].title+"</b>"+"<br/><a href='" + CurrentTabs[i].url + "' target='_blank'>" + CurrentTabs[i].url + "</a><br/><br/>");
}
});
}
window.addEventListener("DOMContentLoaded", GetUrls());
document.getElementById("addBookmark").addEventListener('click',addGoogleBookmark);
function addGoogleBookmark()
{
chrome.bookmarks.create({title:"Extension bookmarks",parentId:?????,url:"http://www.google.com"});
alert("Added to bookmarks");
}
The problem here in the function addGoogleBookmark() what is the parentId?
Any idea?
And this is popup.html:
<!DOCTYPE html>
<html>
<head>
<title>Links Collector</title>
<script src="popup.js"></script>
</head>
<body>
<input id="addBookmark" type="button" value="Add a Google bookmark"></input>
<style>
body {
width:500px;
height: 300px;
}
</style>
</body>
</html>
As described in the official documentation:
parentId ( optional string )
The id of the parent folder. Omitted for the root node.
As the parameter is optional for the chrome.bookmarks.create function, you can omit it for a default usage. In this case, the bookmark will go in the Other Bookmarks folder.
For more advanced usage, take a look at the chrome.bookmarks Documentation

Picture not loading properlly

Good day! I am trying to set a div's background image source with javascript and It doesn't seem to work. I get a weird error in the console from which I have no idea what to made of.
The code may seem a bit lengthy but I will try to make it as clear as possible:
The style basically contains 3 classes. 1 of them is the big box in which the picture and the text are stored. The others are just for the picture (with size) and the label (again with size).
The body contains a simple empty div element which will be dynamically field.
What is left is the javascript file: an array, the object from which the "news"'s different properties will be read (like title, views, image source)
and finally the only function which basically creates new div elements, gives them classes and appends them to the main one. The error is somewhere here.
The entire source code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.newsBox {
width:600px;
height:100px;
background-color:#B3CFDB;
float:left;
border-bottom: solid 1px;
border-bottom-color: #B9DDED;
}
.newsPic {
width:96px;
height:96px;
float:left;
margin-left: 4px;
margin-top:2px;
}
.newsLabel {
height:75px;
width: 500px;
background-color: white;
margin-top:20px;
float:left;
}
</style>
</head>
<body>
<div id="main" class="content"></div>
</body>
</html>
<script>
//create the object array and dummies
var arr = [];
var news = {
title: "",
views: 0,
srs: ""
};
var one = Object.create(news);
one.title = "Bender";
one.views = 132;
srs = "Bender.gif";
arr.push(one);
var two = Object.create(news);
two.title = "Salvation is upon us";
two.views = 777;
srs = "fryFuturama.jpg";
arr.push(two);
var three = Object.create(news);
three.title = "This website is a joke";
three.views = 0;
srs = "fry.jpg";
arr.push(three);
//Set up
var main = document.getElementById("main");
function loadNews() {
for (var i = 0; i < arr.length; i++) {
var p = document.createElement("DIV");
p.className = "newsBox";
main.appendChild(p);
var p1 = document.createElement("DIV");
p1.className = "newsPic";
p1.style.backgroundImage = "url(" + arr[i].srs + ")";
p.appendChild(p1);
var p2 = document.createElement("DIV");
p2.className = "newsLabel";
p2.innerHTML = arr[i].title + "</br></br>" + "Views: " + arr[i].views;
p.appendChild(p2);
}
}
loadNews();
</script>
EDIT: The error: Resource interpreted as Image but transferred with MIME type text/html: "file:///C:/Users/SameTime/Desktop/ObjectSetBackgroundImage.html"
A short answer to your big wall of code
change your
srs = "Bender.gif";
to
one.srs = "Bender.gif";

Unsure how to design JavaScript / jQuery functionality which uses XML to create HTML objects

I'm using JavScript and jQuery to read an XML document and subsequently use the information from the XML to create HTML objects.
The main 'C' nodes in the XML document all have a type attribute, and depending on the type I want to run a function which will create a new html object using the other attributes assigned to that particular 'C' node node.
Currently, I have a for loop which extracts each 'C' node from the XML and also it's attributes (e.g. width, height, x, y).
Also inside the for loop, I have an if statement which checks the 'type' attribute of the current 'C' node being processed, and depending on the type it will run a different function which will then create a new HTML object with the attributes which have been drawn from the XML.
The problem is that there may be more than one 'C' node of the same type, so for example when I'm creating the function that will run when a 'C' node of 'type=1' is detected, I cannot use the 'var p = document.createElement('p')' because if a 'C' node of the same type comes up later in the loop it will clash and override that element with that variable that has just been created.
I'm not really sure how to approach this?
Here is my entire script. If you need me to elaborate on any parts please ask, I'm sure it's not written in the nicest possible way:
var arrayIds = new Array();
$(document).ready(function(){
$.ajax({
type: "GET",
url: "question.xml",
dataType: "xml",
success: function(xml)
{
$(xml).find("C").each(function(){
arrayIds.push($(this).attr('ID'));
});
var svgTag = document.createElement('SVG');
// Create question type objects
function ctyp3(x,y,width,height,baC)
{
alert('test');
var r = document.createElement('rect');
r.x = x;
r.y = y;
r.width = width;
r.height = height;
r.fillcolor = baC;
svgTag.appendChild(r);
}
// Extract question data from XML
var questions = [];
for (j=0; j<arrayIds.length; j++)
{
$(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){
// pass values
questions[j] = {
typ: $(this).attr('typ'),
width: $(this).find("I").attr('wid'),
height: $(this).find("I").attr('hei'),
x: $(this).find("I").attr('x'),
y: $(this).find("I").attr('x'),
baC: $(this).find("I").attr('baC'),
boC: $(this).find("I").attr('boC'),
boW: $(this).find("I").attr('boW')
}
alert($(this).attr('typ'));
if ($(this).attr('typ') == '3')
{
ctyp3(x,y,width,height,baC);
// alert('pass');
} else {
// Add here
// alert('fail');
}
});
}
}
});
});
My example uses the $.each() function in jQuery and adds the element to the <body> tag using a chained function so that you don't ever have to create a variable p.
Even though the author posted their code example after mine was written, I will leave it up here in case anyone else can benefit from it.
See it on jsFiddler: http://jsfiddle.net/gKN4V/
<!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>
<title>Untitled Document</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
var xmlString = '<root>'
+ '<C type="1" x="25" y="30" text="My cool div" />'
+ '<C type="2" x="50" y="75" text="My other div" />'
+ '<C type="1" x="100" y="10" text="My fun div" />'
+ '<C type="2" x="150" y="150" text="My awesome div" />'
+ '</root>';
$(function() {
var xml = $(xmlString);
$("C", xml).each(function(i,o) {
var node = $(o);
switch(node.attr("type")) {
case "1" :
$("<p />", {
"class" : "type1",
css : {
left :node.attr("x") + "px",
top : node.attr("y") + "px"
}
}).text(node.attr("text")).appendTo("body");
break;
case "2":
$("<div />", {
"class" : "type2",
css : {
left :node.attr("x") + "px",
top : node.attr("y") + "px"
}
}).text(node.attr("text")).appendTo("body");
break;
}
});
});
</script>
<style type="text/css">
.type1 {
position: absolute;
border: solid 1px gray;
font: normal 12px Arial, Helvetica, sans-serif;
}
.type2 {
position: absolute;
border: solid 1px green;
font: bold 12px Arial, Helvetica, sans-serif;
color: green;
}
</style>
</head>
<body>
</body>
</html>
I cannot use the 'var p = document.createElement('p')' because if a 'C' node of the same type comes up later in the loop it will clash and override that element
Just don't use fixed variable names. Let your loop add elements to an array instead:
var elementList = [];
var Cs = xml.getElementByTagName("C");
for (var i=0; i<Cs.length; i++) {
elementList.push( whateverYourFunctionIsThatCreatesHtmlNodes(Cs[i]) );
}
or add them right to the DOM in the loop body.

Categories

Resources