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
Related
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>
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
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?";
}
});
I am trying to post some json data to REST web service implemented with Jersey framework. I am not using JAXB or jquery but only javascript.
I verified that formed json is correct but in spite of setting content type "application/json", on server it is received as "application/x-www-form-urlencoded".
Here is my code:
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = {};
var elem = document.getElementById('frmMain').elements;
//alert(elem.length);
for(var i = 0; i < elem.length-1; i++)
{
str[elem[i].name] = elem[i].value;
}
document.getElementById('lblValues').innerHTML = str;
var json = JSON.stringify(str);
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(document.getElementById('frmMain').method,
document.getElementById('frmMain').action);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-Length",json.length);
xhr.setRequestHeader('Accept', 'application/json');
//alert(json);
// send the collected data as JSON
xhr.send(json);
xhr.onloadend = function() {
// done
}
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" action="/JerseyTest/rest/postUser"
method="post">
<input name="firstName" value="harry" /> <input name="lastName"
value="tester" /> <input name="toEmail" value="testtest#test.com" />
<br /> <input type="submit" value="Test"
onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
On the server side:
package com.example.jersey.test;
import javax.ws.rs.*;
#Path("/postUser")
public class JsonTest {
#POST
#Consumes("application/json")
#Produces(MediaType.TEXT_PLAIN)
public String pingPong(String json) {
return "Answer is "+ json;
}
}
I am new to web development and not sure on what I am missing in above code.
I am answering my own question for those who may visit this later. The code above is correct and works well except the fact that the url is been hit twice. First time, for submit button's default action and then as per our script by XMLHttpRequest.
This I came to know after I checked the headers in Httpfox which showed error as NS_BINDING_ABORTED.
After changing the input type to button from submit, all is working fine.
The code provided below doesn't show all the content of that page.
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript">
var rootdomain="http://"+window.location.hostname
alert(rootdomain);
function ajaxinclude(url) {
var url=rootdomain+url;
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
writecontent(page_request)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 ||
page_request.status==200)
document.getElementById("write").innerHTML=page_request.responseText;
}
</script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !" onclick="ajaxinclude('/songcake/index.php');"/>
</body>
</html>
Please Help
Thanks.
You need to add a closure that reacts upon the completion of the document loading process.
page_request.onreadystatechange = function() {
if(page_request.readystate == 4) {
// data handling here
}
}
As pointed out though, using jQuery will make things a lot easier.
Edit: To clarify, your AJAX call does check for the connection status (request.status), but not for the loading status (request.readystate). Your document probably did not load completely.
Here's a reference for the W3.org XMLHTTPRequest API: http://www.w3.org/TR/XMLHttpRequest/ .
Edit2: Btw, an <iframe> element would solve your problem with a lot less code.
Edit 3: Code
function ajaxinclude(url) {
//...
page_request.open('GET', url, false) //get page synchronously
//<> add onreadystatechange handler
page_request.onreadystatechange = function() {
if(page_request.readystate === 4) {
if(page_request.state === 200) {
//call function on success
writecontent(page_request.responseXML)
}
}
}
page_request.send(null)
}
Some additions:
if you put your ajax call into the <HEAD> you need to either create the dom elements you want to append data to as they are not available when the runtime runs through (which might lead to a dom error); or you need to add an on dom load event handler.
Synchronous calls are not properly implemented in some browsers and this might lead to errors too.
Why you should not use jQuery? You can do this simple as below..
$("#write").load("/songcake/index.php");
[EDITED]
Below you can see the completed code
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src='scripts/jquery.js'></script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !"
onclick="$('#write').load('/songcake/index.php');"/>
</body>
</html>
You can download jQuery from here : http://jquery.com/
The source for my answer you can find here : http://api.jquery.com/load/
try to use FireBug
FireBug show you state of your request.
If it 200 and you see that in reqest answer (in firebug) broken data then
you should check your index.php script