dynamically creating HTML divs with JS from XML - javascript

Im looking for a bit of Yoda like guidance on a project im working on. Im trying to dynamically generate div's in a web page based around XML data which is read in from a php server. Im punching a bit above my experience weight which is good for learning.
Was wondering if someone could point me in the right direction as far a tutorials or give me some guidance to see if im on the right track etc.
The XML im loading in is...
<item>
<id>1</id>
<name>Johnothan</name>
<message>hello world</message>
</item>
<item>
<id>2</id>
<name>Fredrico</name>
<message>hello world</message>
</item>...etc
My Ajax function to call.
function ajax(site, params){
var xmlhttp;
var i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML;
}
}
xmlhttp.open("POST", site, false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(params);
}
JS Div generation
function information(){
xmlReturned = xmlDoc.getElementsByTagName("item");
for (i=0; i<xmlReturned.length; i++){
newDiv(i);
}
function newDiv(i){
var id = xmlReturned[i].getElementsByTagName("id")[0].firstChild.nodeValue;
var name = xmlReturned[i].getElementsByTagName("name")[0].firstChild.nodeValue;
var message = xmlReturned[i].getElementsByTagName("message" [0].firstChild.nodeValue;
//Now im trying to place the dynamic XML information within a table with in a new DIV in the HTML.
}
My HTML is pretty basic it calls the information() function with the body tag loads.
Am I looking in the right direction?? Can someone help me out or recommend a tutorial?
Thanks for your time

Try using jQuery. It simplifies the task that you are trying to do.
http://api.jquery.com/category/manipulation/
Eg.
var newDiv = $('<div/>').text(sampleText);
parentDiv.append(newDiv);
Useful example of using jquery to do your task:
http://think2loud.com/224-reading-xml-with-jquery/

i have this code in a jquery popup here is the code
jQuery(document).ready(function(){
var showmask = function() {
var dialogLeft = ((jQuery(window).width() - jQuery("#outerFbDialog").outerWidth()) / 2) + jQuery(window).scrollLeft() + "px";
var dialogTop = "100px";
/* uncomment this to place dialog in the center of window.
var dialogTop = ((jQuery(window).height() - jQuery("#outerFbDialog").outerHeight()) / 2) + jQuery(window).scrollTop() +"px";
*/
jQuery("#themask").css({'width':jQuery(window).width(),'height':jQuery(document).height()});
jQuery("#themask").fadeTo('slow',0.7);
jQuery("#outerFbDialog").css({'left': dialogLeft,'top':dialogTop});
jQuery("#outerFbDialog").show();
$('#themask').click(function () {
jQuery(this).hide();
jQuery("#outerFbDialog").hide();
});
}
// check for escape key
$(document).click(function(e) {
jQuery("#themask").hide();
jQuery("#outerFbDialog").hide();
});
showmask();
});

Related

Uploading Images to WYSIWYG editor and having default styling applied

I have created a wysiwyg text editor for my site and am trying to work with images.
So far I've got my image being uploaded and being added to my text editor where I want it using something like this:
$("#upload_wysiwyg_image").unbind("click").bind("click", function() {
var formData = new FormData();
var image_to_upload = document.getElementById("wysiwyg_image").files[0];
formData.append("wysiwyg_image", image_to_upload);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText.includes('uploaded')){
var upload_string = this.responseText;
var image_name = upload_string.replace("uploaded ","")
var image_path = '../media/wysiwyg_images/'+image_name;
execCmdWithArg('insertImage', image_path);
}
}
};
xmlhttp.open("POST", "upload_wysiwyg_image.php", true);
xmlhttp.send(formData);
});
function execCmdWithArg (command, arg){
richTextField.document.execCommand(command, false, arg);
}
I want to be able to format the image at this point when it is being inserted. So for instance set a max-width/max-height or be able to select a float value for positioning.
Can this be done at this point while it is being inserted or will I need to insert it, and then call another function to set values for styling?
If anyone can point me in the right direction for this it would be greatly appreciated.

Call javascripting and display result in right hand frame

I've a menu on the left side of a frame.
I'm trying to call a javascript that will load a new html in the right side of the frame generated from XML data and XSL template.
The code to do it in one page with fixed parameters works fine. The two issues I struggle with is:
How to make it flexible so I can use a different xml data and template on the call to the script
How to present the data in the right hand frame pane.
This is the code for the left hand pane:
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult(xmlid,xslid)
{
xml = loadXMLDoc("XMLDATA/xmlid");
xsl = loadXMLDoc("XMLDATA/xslid");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("example").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body>
<p>TEST</p>
<p>TEST</p>
<div id="example" />
</body>
</html>
If I omit the both arguments in the script call:
TEST
and assign the data sources in the parameters here:
xml = loadXMLDoc("XMLDATA/cdcatalog.xml");
xsl = loadXMLDoc("XMLDATA/cdcatalog.xsl");
Then it works on the same page.
I'm not a programmer so some help would be great.
You're not using the variables that you're passing in, you're simply using static text.
At the start of function displayResult(xmlid,xslid) change...
xml = loadXMLDoc("XMLDATA/xmlid");
xsl = loadXMLDoc("XMLDATA/xslid");
To...
xml = loadXMLDoc(xmlid);
xsl = loadXMLDoc(xslid);
Update - in response to the OPs comments...
If you want to move elements around the page, I would seriously consider looking at jquery which will easily allow you to detach the items and append them to another area.
For example...
$(function(){
var $rightArea = $("#rightarea");
$("#leftarea *").each(function(){
$(this).detach().appendTo($rightArea);
});
});

I can not figure out how to load second time posts at page end

I am using XMLHttpRequest to retreive more posts from mySQL database to show on the page.
It is working fine the first time, but the second time and times after that it doesn´t know which posts to acquire, so it will keep getting the second times over and over again.
What triggers the Send Request is not a button with a certain ID. It is a Load More Data At Page End.
This is the code for Requesting XMLdata:
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); }
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
wrap.innerHTML += xmlhttp.responseText; }
}
xmlhttp.open("GET","getposts.php?q="+nextId);
xmlhttp.send();
And here is the code for Load More Data At Page End:
function yHandler(){
var wrap = document.getElementById('wrap');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight)
{
//--- Requsting XMLdata goes here ---
}
var status = document.getElementById('status');
status.innerHTML = contentHeight+" | "+y;
}
window.onscroll = yHandler;
I have tried to use $_SESSION for saving the time user has requested posts, so I can add +1 to it each time but the value will increase like crazy. First it is 0 then 4 and the third time it´ll be 9 or something like that.
Here is how I use SESSION at the very first before HTML tag:
session_start();
if(isset($_SESSION['ordning']))
{
$_SESSION['ordning'] = $_SESSION['ordning'] + 1 ;
}
else
{
$_SESSION['ordning']=0;
}
Do anybody know of a way to do this? I am stuck like H ... l
Thanks a lot for help!
If nextId is a reference to the first post that you want to retrieve from the XHR, you need to increase it each time you request the new posts, either by a set amount while sending the request or based on the number of responses you get from the server.
If it's not, you should add another parameter to the URL that you are requesting from the server such as '&postIndex='+postIndex, and increment pageIndex by the number of responses that you get from the server each time, as I mentioned above.
On the server side, simply start your SQL query from the data received in pageIndex.

Create new div element from scratch on mouseovering a text with DOM

I'm trying to work on getting "a tooltip" on hovering a text.
This tooltip should be placed below the text. The tooltip should get its content from a database but I can handle that part, and styling it with css. Only problem here is that I can't create a new div element from scratch when mouseovering.
My current code uses existing div element but the code is supposed to create a new div element where place the code.
<script>
function createTooltip(str)
{
if (str == "" || !str)
{
return;
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "tooltip.php?s="+str, true);
xmlhttp.send();
}
function removeTooltip()
{
document.getElementById("txtHint").innerHTML = "";
}
</script>
<p><br>
Test
<br><br>
<div id="txtHint"></div></p>
The tooltip.php file has this content in it:
<?php
$q = intval($_GET['s']);
echo $q;
?>
For now it just prints the rel attribute in function. Now what I really want it to do is to create completely new div with the xml response in it, instead of an existing div. So this tooltip should appear below the text, like with this existing div. In future I will make it a hover div element, so it just hovers on all content.
Thank you for your time, I appreciate it.
You can use .hover() function to define both mouseover/mouseout events. You can use .after() to append new DIV and .remove() to remove it.
Assuming this is the element you hover over:
Test
This sample demonstrates the effect:
$('#test').hover(
function() {
var text = "Tooltip for rel: " + this.rel;
$(this).after($("<div></div>").html(text).addClass("tooltip"));
},
function() {
$(this).next().remove();
}
)
And here's live demo: http://jsfiddle.net/3LgWk/1/
Oh and jQuery makes AJAX calls a lot easier as well - give it a look when you get a chance.

Problem creating gui from xml -> Strange CPButton behaviour

Hallo,
I'm new to objective-j and cappuccino and just have tried to create a
small application, that creates the gui dynamically from a xml file.
Unfortunately it works only partially. It seems that the button
regions are disorder. This means, that the buttons also response if
I click besides the button....
Please help me. I dont get it..
- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
mControlList = [CPArray alloc];
theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero()
styleMask:CPBorderlessBridgeWindowMask],
contentView = [theWindow contentView];
[contentView setFrame:[[contentView superview] bounds]];
[contentView setAutoresizingMask:CPViewWidthSizable |
CPViewHeightSizable];
// Loadxmlfile
var xhttp;
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest()
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xhttp.open("GET","test.xml",false);
xhttp.send("");
xmlDoc = xhttp.responseXML;
//Get controls nodeand iterate through all controls
var node = xmlDoc.getElementsByTagName("controls")[0];
for (var i=0; i<node.childNodes.length; i++) {
if(node.childNodes[i].nodeName=="button"){
var item = node.childNodes[i];
var name = item.attributes["name"].nodeValue;
var text = item.getElementsByTagName("text")
[0].childNodes[0].nodeValue;
var x= item.getElementsByTagName("rect")
[0].attributes["x"].nodeValue;
var y= item.getElementsByTagName("rect")
[0].attributes["y"].nodeValue;
var width= item.getElementsByTagName("rect")
[0].attributes["width"].nodeValue;
var height= item.getElementsByTagName("rect")
[0].attributes["height"].nodeValue;
var b = [[Button alloc] InitWithParent:contentView Text:text X:x
Y:y Width:width Height:height];
[mControlList addObject:b];
}
}
[theWindow orderFront:self];
}
#implementation Button : CPObject
{
CPButton _button;
}
- (Button)InitWithParent:(CPView)contentView Text:(CPString)text X:
(int)x Y:(int)y Width:(int)width Height:(int)height
{
_button = [[CPButton alloc] initWithFrame:
CGRectMake(x,y,width,height)];
[_button setTitle:text];
[_button setTarget:self];
[_button setAction:#selector(cmdNext_onClick:)];
[contentView addSubview:_button];
return self;
}
- (void)cmdNext_onClick:(id)sender
{
}
#end
Cappuccino gives you most of this functionality for free.
You can load files by using a CPURLConnection.
Also Atlas (or Interface Builder and nib2cib) will automatically create cib files for you, Cappuccino itself already knows how to build up it's UI from a cib files.
If you really want to implement your own system to do this, could you please provide the actual XML you are trying to load? Also try loading the button without using the XML. For example:
var myButton = [CPButton buttonWithTitle:#"My Cool Button"];
[contentView addSubview:myButton];
+ buttonWithTitle: will automatically call - sizeToFit on the initialized button, so you can just add it to your contentView and it should be visible with the appropriate size.

Categories

Resources