How to create and display XML through Javascript/PHP/ - javascript

I have some javascript objects that represent the XML that i want to create.
I need a simple way to create/ generate XML, and then somehow hand it over/ show it to the user in a clean way (structurized, like in the screenshot example).
I've been experimenting and researching but haven't yet foudn what i am looking for.
Current test code:
function exportXML(){
var XML = document.createElement("div");
var Node = document.createElement("testing");
Node.appendChild( document.createElement("testingOne") );
Node.appendChild( document.createElement("TestingTwo") );
Node.appendChild( document.createElement("TestingThree") );
XML.appendChild(Node);
//alert(XML.innerHTML);
xmlWin = window.open("","xmlWin","width=800,height=600");
xmlWin.document.write("XML: \n" + XML.innerHTML);
}
xml example:
-<station stationNr="WP006">
-<definitionstat>
<admtyp>A</admtyp>
<responsible>SIEMENS</responsible>
<bildnam>B12</bildnam>
<stattyp>T</stattyp>
</definitionstat>
</station>
What i would like to have:

To create XML:
$xml = new \DomDocument("1.0","UTF-8");
$xml->formatOutput = true;
$xml_data = $xml->createElement("Element_Container","Container Value");
$xml_data = $xml->appendChild($xml_data);
$xml->saveXML();
$xml_status->save($xml_file_path);
To display in formatted way:
$xml = simplexml_load_file($xml_file_path);
foreach ($xml->children() as $key => $child)
{
// Your formatted output here...
}

Related

jquery - separate JSON and HTML from AJAX Response

I have a AJAX response something like this.
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}]<table id="table"></table>
It has both JSON and HTML in the response.
I wanted to separate those two things.
And use the JSON for a chart function I've created.
And then append that table to a div.
Any suggestions will be very much fruitful.
Thanks in advance.
In php
$array = 'Your json array';
$html = 'Your html codes';
Make a single array with two keys
$newArray = array();
$newArray['json'] = $array;
$newArray['html'] = $html;
echo json_encode($newArray);
In Jquery
DataType: 'JSON',
success:function(response){
response.json = 'This is your json';
response.html = 'This is your html';
}
Add the HTML to the JSON response and use it like you would your other values (make sure to escape your html). Also use JSONLint to make sure your JSON is valid.
[
{
"label": "label",
"label1": "67041",
"label2": "745",
"label3": "45191",
"label4": "11‌​464",
"html": "<table id=\"table\"></table>"
}
]
While I recommend you not to do that, because is to geeky and hard to maintain, You can solve id by detecting the JSON object using regex, like this:
var data = '[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}]<table id="table"></table>';
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str.substr(1, json_str.length-2) + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}
//html_data = [text] <table id="table"></table>
The Best Solution would be to use a template engine like jquery templates to define your html, and then get your data via $.json and evaluate it agains your desired template already on the client, no need to be sending it right along with your data and be doing that kind of processing in run time.
JavaScript
// assuming you keep receiving this
var data =
'[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"},'
+'{"label":"label2","label1":"0000","label2":"222","label3":"333","label4":"11‌333"}]'
+'<table id="table"></table>';
// parse the data with regex
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1": ...
//html_data = [text] <table id="table"></table> ...
// then use jquery templates to render it
var data = json_data;
$('body').append(html_data);
$('#trTemplate').tmpl(data).appendTo('#table');
HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${label}</td>
<td>${label1}</td>
<td>${label2}</td>
<td>${label3}</td>
<td>${label4}</td>
</tr>
</script>
CSS
#table, td{ border:1px solid #000; padding:5px; }
Here is an working JSFiddle example for you to test it.
Note how this works when you have more than one {json object, it's creates more lines in the table :) }
If you use jquery templates only, and now assuming that you can actually modify your output than the best thing to do is:
New JavaScript Version of Code with template only and no HTML on 'data'
$.json('http://server.com/url/service/someservice.something', function(data){
$('body').append(<table id="#table></table>");
$('#trTemplate').tmpl(data).appendTo('#table');
})
Much more simple don't you think?! Hope this helps guiding you on the right path.
Link to jquery tmpl: http://knockoutjs.com/downloads/jquery.tmpl.min.js.
Although after understanding my example, if you are building a system to scale on, and you are not just doing a simple widget app, I would recommend you to check something more robust in terms of functionalities and support like Knockoutjs as jquery tmpl has been deprecated, unfortunately.

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Flex: Sending XML with Javascript

I am attempting to send over an XML string to Flex via javascript. This is the XML I am creating with javascript.
var xml = "<template>";
xml += "<folder>";
xml += "<lab>";
xml += "Are You working?";
xml += "</lab>";
xml += "</folder>";
xml += "</template>";
return xml;
I have confirmed that "<template><folder><lab>Are you working</lab></folder></template>" is getting sent via an Alert box.
In the Flex application here is where thing are going wrong. I am calling this function on creationComplete and attempting to populate a comboBox:
/ variable declarations---------------------------------------
[Bindable]
private var templateFolder:ArrayCollection = new ArrayCollection();
// event handlers-----------------------------------------------
private function init(event:FlexEvent):void {
var labList:SyncRequestResult=CSXSInterface.instance.evalScript("templateHub");
templateFolder = labList.data.template.folder;
}
/ variable declarations---------------------------------------
[Bindable]
private var templateFolder:ArrayCollection = new ArrayCollection();
// event handlers-----------------------------------------------
private function init(event:FlexEvent):void {
var labList:SyncRequestResult=CSXSInterface.instance.evalScript("templateHub");
templateFolder = labList.data.template.folder;
}
And then finally to my component:
<mx:ComboBox id="labFolderList"
x="53" y="11"
width="212"
dataProvider="{templateFolder}"
labelField="lab"></mx:ComboBox>
I'm a newbie at Flex and not sure that I am treating the data correctly in Flex. Any ideas where I am screwing this up?
Thanks for your help

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

Converting HTML string into DOM elements?

Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()

Categories

Resources