Loading .txt file into textarea Javascript? - javascript

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>

You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object

Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>

This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area

One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)

window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});

Related

How to render HTML file using JavaScript [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

HTML Form Input Fields to read and write XML file

I am currently trying to build an HTML form with input fields to read an XML file and write back with changes. The first step is retrieving values on page load into the input fields but it doesn't want to work
<body>
<h1>Config Page</h1>
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
<b>Site Collection:</b> <span id="siteCollection"></span><br>
</div>
<script>
var xmlhttp, xmlDoc;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Configuration/config.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElement
document.getElementById("siteURL").value.innerHTML =
xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue;
document.getElementById("siteCollection").innerHTML =
xmlDoc.getElementsByTagName("siteCollection")[0].childNodes[0].nodeValue;
function myFunction() {
alert(siteURL + "is the site Url")
}
</script>
<button onclick="myFunction()">Get message value</button>
I know the XML is pulling through ok because the siteCollection span item works, but the input field does not.
Any help would be much appreciated.
Thank you.
Maybe if you use jQuery you can do it as following
http://codepen.io/Daethe/pen/dXWjJo
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
</div>
<button onclick="myFunction()">Get message value</button>
<script>
function myFunction() {
var xmlHttp = jQuery.parseXML('<?xml version="1.0" encoding="utf-8"?><config><siteURL>http://localhost/</siteURL></config>');
var xmlDoc;
xmlDoc = xmlHttp.documentElement;
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
</script>
Thanks to Daethe for putting me on the right track. I found my solution to read an xml file into a HTML input field form
for the javascript...
var xmlpath = "../configuration/test.xml"
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlpath, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
function loadFunction() {
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
For the page...
<script src="/Script/form.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<html>
<br>Site URL (EG: http://intranet)</br>
<input type="text" id="siteURL" name="siteURL" value="blank..." />
<button onclick="loadFunction()">Load Configuration</button>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<title>Please Check Data</title>
<script type="text/javascript">
function readXMLFile() {
var i;
var xml = new XMLHttpRequest();
xml.open('GET', 'projectRelatedData.xml', false);
xml.send();
var xmlData = xml.responseXML;
xmlData=(new DOMParser()).parseFromString(xml.responseText,'text/xml');
var projectData=xmlData.getElementsByTagName("project");
//alert(projectData.length);
for(i=0;i<projectData.length;i++)
{
var name=projectData[i].getElementsByTagName("name")[0].firstChild.data;
var imageName=projectData[i].getElementsByTagName("imagePath")[0].firstChild.data;
var pdfName=projectData[i].getElementsByTagName("pdfPath")[0].firstChild.data;
var description=projectData[i].getElementsByTagName("description")[0].firstChild.data;
var amount=projectData[i].getElementsByTagName("amount")[0].firstChild.data;
//alert("number of Project : "+projectData.length);
document.write(name+'<br>');
document.write(imageName+'<br>');
document.write(pdfName+'<br>');
document.write(description+'<br>');
document.write(amount+'<br>');
}
}
</script>
</head>
<body>
<button onclick="readXMLFile()">Click</button>
<p id="ccc"></p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<projectWebsite>
<project>
<name>CARGO SHIPPING</name>
<imagePath>CARGOSHIPPING.PNG</imagePath>
<pdfPath>cargoShipping.pdf</pdfPath>
<description>
Cargo shipping is all about booking cargo to move from one place to another. Owner can add new shipsand he can also track ships.User can register for cargo and he can also track ships.Admin has the right to view detailsof owner, to add a new company and also update price of ship. This software hasa very nice GUI to give a very nice presentation of a cargo management system.
</description>
<amount>4000</amount>
</project>
<project>
<name>E-BAZZAR</name>
<imagePath>ebazzar.PNG</imagePath>
<pdfPath>eBazar.pdf</pdfPath>
<description>
This project emphasizes on taking bookings of pat ient in a web portal system.Patient can search for the doctor and book for appointment . Doctor can check and confirm appointment so patient can visit accordingly.Also admin is provided to add doctors in the portal,moreover customer list can be seen as well.
</description>
<amount>4000</amount>
</project>
</projectWebsite>

How to detect and print changing variables LESS

I want to create a simple script that changes LESS variables and print the CSS output in a div.
this is my HTML
<input type="text" id="choose-color" onchange="ModifyColorsInLess()">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
This is my js
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status === 200 && xmlhttp.readyState === 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","css/styles.less",true);
xmlhttp.send();
}
function ModifyColorsInLess() {
less.modifyVars(
{
'#colore-body': $("#choose-color").val()
}
);
}
The script prints CSS code correctly, but if i insert a new color value in the input type="text" and call the writeCSS function, it doesn't print my variable edit.
I think the problem is that "modifyvar" does not change the file "styles.less", so when I call the function writeCSS() does not detect changes made.
is there a way to print the css dynamically detecting changes made with modifyvar?
update
When you allow the compiled styles are directly applied on your page, you can simply call `modifyVars as follows:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<link rel="stylesheet/less" type="text/css" href="t.less">
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
less.modifyVars({
'colore-body': document.getElementById('choose-color').value
});
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
Demo: http://plnkr.co/14MIt4gGCrMyXjgwCsoc
end update
Based on How to show the compiled css from a .less file in the browser?, How to update variables in .less file dynamically using AngularJS and Less: Passing option when using programmatically (via API) (you should also read: http://lesscss.org/usage/#programmatic-usage) you should be able to use the code like that shown below:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var options = {}
options['modifyVars'] = {'colore-body' : document.getElementById('choose-color').value}
lessCode = xmlhttp.responseText;
less.render(lessCode, options, function (error, output) {
if(!error) {
document.getElementById('lesscode').innerHTML = output.css;
}
else document.getElementById('lesscode').innerHTML = '<span style="color:red">' + error + '</span>';
});
}
};
xmlhttp.open("GET","styles.less",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
demo: http://plnkr.co/YbdtOwOeQPC1k9Vq4ZBv
And finally based on Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload you can prevent caching of your source file with the following code:
xmlhttp.open("GET","t.less?_=" + new Date().getTime(),true);
In the above the env: "development" setting prevents your source files from caching. To clear the cache otherwise, you should call less.refresh(true) before your less.render call.
i have another little problem, if in my less file there is a reference
to another less file like this(#import "another.less") script doesn't
work.
Make sure that another.less in the above is in the same folder as your styles.less file. Notice that import (when using less in browser) are read with a XMLHttpRequest too. So your imported files should be readable by browser and their paths should be relative to the styles.less file. Also see http://lesscss.org/usage/#using-less-in-the-browser-relativeurls

how javascript send blank line to php?

I write a demo like this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
window.onload = init;
function init() {
var btn = document.getElementById('submit');
btn.onclick = function() {
var str = document.getElementById('testText').value;
alert(str);
var xmlHttp = new XMLHttpRequest();
var url = 'test.php?str=' + str;
xmlHttp.onreadystatechange = function(){
var str = xmlHttp.responseText;
document.getElementById('testText').value = str.toLocaleUpperCase();
};
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
};
}
</script>
</head>
<body>
<form action="test.php" method="POST">
<textarea name="testText" id="testText" cols="30" rows="10"></textarea>
<input type="button" value="submit" id="submit">
</form>
</body>
</html>
It send a GET to server, and the php just return what it get, then js show it by uppercase(write this because of system ask me to write more detail of code)
I write some text in textarea tag like
write some thing
write other thing
and output is
WRITE SOME THING WRITE OTHER THING
but I want to remain the blank lines, and expect output like this
WRITE SOME THING
WRITE OTHER THING
how should I do?
When you send your data to PHP, you need to convert your text into URL format.
var url = 'test.php?str=' + encodeURIComponent(str);
When you output the PHP into an HTML document, you need to convert your text into HTML.
Most elements do not treat whitespace as significant, so you need to convert the new lines into line break elements or do some other kind of formatting. (In general, you want to use something smarter, like Markdown syntax, but I'll use nl2br for this simplistic example):
<div>
<?php
$data = $_GET['str'];
$safe_data = htmlspecialchars($data);
$formatted_data = nl2br($safe_data);
echo $formatted_data;
?>
</div>
or, if you are outputting into an element with significant whitespace
<textarea>
<?php
$data = $_GET['str'];
$safe_data = htmlspecialchars($data);
echo $safe_data;
?>
</textarea>
You can use the NewLine character entity, which can be expressed using any of the following:
&NewLine;
Like so:
write some thing&NewLine;write other thing
...or:
write some thing
write other thing
...or:
write some thing
write other thing
Demo
<textarea>write some thing&NewLine;write other thing</textarea>
<textarea>write some thing
write other thing</textarea>
<textarea>write some thing
write other thing</textarea>

Help with parsing XML with javascript?

I am trying to use Java-script as a client for java based restful web-service. The service is a survey maker. I am having trouble getting the function to work. The server side of the service is in Google App Engine. In the code below the function uses http get to get xml representing a list of surveynames, then gets the data from the xml and puts it in a html table. The code is not working, so it would be great if some one could check it to see if I am doing this correctly or I am doing something wrong. I have never programed in javascript so I would also like to know if I need to import a library to use AJAX or is it supported by the browser?
<!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>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>View Surveys</title>
</head>
<SCRIPT>
function getSurveyNames(){
var url = "http://survey-creator.appspot.com/rest/surveymakerpro/allsurveys";
var xmlhttp;
// AJAX code for Mozilla, Safari, Opera etc.
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
// AJAX code for IE
else
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>";
var surveyNames = xmlhttp.responseXML.documentElement.getElementsByTagName("surveys")[0];
for(var i = 0; i < surveyNames.length ;i++){
var surveyNameChildNode = surveyName[i].childNodes[0];
var name = surveyNameChildNode.nodeValue;
HTMLSurveyNames += "<tr><td>"+name+"</td></tr>";
}
//div tags
document.getElementById('displayNames').innerHTML = HTMLSurveyNames;
}
}
</SCRIPT>
<body>
<p>View Survey</p>
<form method="post">
<input name="GetSurveys" style="width: 103px" type="button" value="View all surveys" onClick=getSurveyNames(); /></form>
<p>Here Goes a Table of Surveys</p>
<div id="displayNames">
<p>Enter the survey you wish to take:</p>
<form method="post">
<input id="surveyName" name="SurveyName" style="width: 140px" type="text" value="Enter Survey Name...." /></form>
<form method="post">
<input name="Submit2" type="submit" value="Get Survey" /></form>
<div id="displaySurvey"></div>
</div>
<p>
<input id="sendtoserver" name="Submit3" type="submit" value="Submit TakenSurvey" /></p>
</body>
</html>
This is the xml I want to parse
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><surveyNames><SurveyList><surveys>DragonBallZ</surveys><surveys>FootballSurvey</surveys><surveys>NewsSurvey</surveys><surveys>PennstateSurvey</surveys></SurveyList></surveyNames>
You're sending off an asynchronous request, but then attempting to immediately process the result before this request will have finished.
You should assign a handler to xmlhttp.onreadystatechange that will be executed as your request progresses. You currently assign xmlhttpChange to this property, but you don't show what xmlhttpChange is. You should be doing something like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// XML parsing code goes here
}
}
You do not need to import any libraries to use Ajax
Be careful with lines like HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>"; You should always use the var keyword when declaring variables, to avoid creating/modifying globals implicitly.
"<table border='1'><tr>Survey Names<th></th></tr>"
should be
"<table border='1'><tr><th>Survey Names</th></tr>"
things will work a LOT better.
there is a cross-browser XML librari for javascript at http://www.softxml.com/softxmllib/softxmllib.htm
I believe XMLHTTPRequest() is specific to IE. there are versions for other browsers. http://en.wikipedia.org/wiki/XMLHttpRequest

Categories

Resources