How can i output this content to a textarea? - javascript

I have tried to pass on the text from a php page into my html page, as described by Chris Bakers answer (javascript, not jquery).
Call php function from javascript
The code works, if i use the normal text (id=output), but i would like to output the text to a textarea (id=text1) instead of a normal text, just changing the id does not work.
This is my code:
<html>
<head>
</head>
<body>
<textarea id="text1" style="background-color: #969696" cols="50" rows="10" readonly></textarea>
<div id="output">waiting for action</div>
</body>
<script>
function getOutput() {
var value = document.getElementById("artikelnr").value;
var file = selectedValue()+".csv";
getRequest(
"verarbeitung.php?eingabe="+value+"&eingabe2="+file, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('text1');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('text1');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
</script>
</html>

Because you should use .value instead of .innerHTML.
Reference: JavaScript get TextArea input via .value or .innerHTML?

It is not setInnerHtml, textarea has a value attribute. Not really logical but well...
mad you a fiddle:
document.getElementById("bla").value = "test";
<textarea id="bla" readonly >Initial Value</textarea>

Related

Global Javascript variable from AJAX JSON request

Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console
To clarify my question, how can I retrieve a global variable from an AJAX JSON request
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class="src">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>
<div id="Name">Sachin</div>
</td>
<td>
<div id="Country">India</div>
</td>
</tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</div>
The best way to approach this is by using what's called a callback function. A callback function is a function that is invoked when specific event takes place. In your case that event is the data being retrieved from your JSON endpoint (URL).
The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. If you want to make that data also accessible globally, part of the callback function can update your global variable.
In the updated code below we first declare a global variable globalJSON that holds our data. Before you receive any data (i.e. before you click the button) the value of globalJSON.data will be null. Once the data is received the callback function updateView() is called with the received data. Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (i.e. updating the required HTML elements).
You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked.
// declare your global variable that will get updated once we receive data
var globalJSON = {
data: null
}
// this gets executed the moment you load the page - notice the value is null
console.log(globalJSON.data);
// this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function
function updateView(data) {
// this will update the value of our global variable
globalJSON.data = data;
// this is the rest of the logic that you want executed with the received data
document.getElementById("Name").innerHTML = data.name;
document.getElementById("Country").innerHTML = data.country;
// this will show that the global variable was in fact updated
console.log(globalJSON.data);
}
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
updateView(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText);
But you won't have any way of knowing when it's defined outside of the event handler. However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value.
full code:
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(JSON.parse(http_request.responseText));
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
Declare a variable at first like var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ). access the variable in your function. A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. As a result you got an error something like that
Blocked loading mixed active content "http://www.tutorialspoint.com/json/data.json"
So change the url also to https://www.tutorialspoint.com/json/data.json.
Then you can parse the result as you want.
<title>tutorialspoint.com JSON</title>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON();">Update Details </button>
</div>
<script>
function loadJSON(){
var jsonObj= '';
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
console.log(jsonObj);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>

JSON data update not showing up on webpage

I want the value on my webpage to change, as the value in the JSON file changes. I wrote an interval function- intervalFunction() but the page does not update. Here is my code :
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
var myVar;
function intervalFunction() {
myVar = setInterval(loadJSON(), 100);
}
function loadJSON(){
var data_file = "http://52.21.92.17/balance";
var http_request = new XMLHttpRequest();
try{
http_request = new XMLHttpRequest();
}catch (e){
// IE
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Address").innerHTML = jsonObj[0].address;
document.getElementById("Balance").innerHTML = jsonObj[0].etherBalance;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body onload="intervalFunction()">
<table class = "src">
<tr><th>Address</th><th>Balance</th></tr>
<tr><td><div id = "Address"></div></td>
<td><div id = "Balance"></div></td></tr>
</table>
</body>
</html>
Furthermore, another question I have is when use index [1], I can see data on the webpage, but if I use index [0], the first set of data in the array does not appear. Help would be appreciated.
function intervalFunction() {
myVar = setInterval(loadJSON(), 100);
}
is like saying:
function intervalFunction() {
var something = loadJSON();
myVar = setInterval(something, 100);
}
You're calling loadJSON() once, immediately, then asking setInterval() to call its result as a function.
You mean to say:
function intervalFunction() {
myVar = setInterval(loadJSON, 100);
}

Uncaught TypeError: Failed to execute 'importStylesheet' on 'XSLTProcessor': parameter 1 is not of type 'Node'

I am trying to use XSL to translate an XML file into a neat table. For that I used the examples provided by W3schools which can be located here as a starting point. Yet the browser(chrome) is throwing the error that is described in the title of this post. I even tried copying the exact same example on W3 only to be met with the same error. Tried debugging in Firefox, this is the console output
TypeError: Argument 1 of XSLTProcessor.importStylesheet is not an object.
A similar question was posted before and the solution was in changing the model from synchronous to async. I tried doing that through the onreadystatechange method but without success. Here is the code I worked with.
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseXML;
}
};
xhttp.open("GET", filename);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
}
function displayResult()
{
xsl = loadXMLDoc("cdcatalog.xsl");
xml = loadXMLDoc("cdcatalog.xml");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("dataTable").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("dataTable").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="dataTable" />
</body>
Thank you for all the help!
Here is an example of two asynchronous requests where the callback of one event handler starts the next request whose callback does the transformation. To keep it simple, I have used onload instead of onreadystatechange, if you really need support for old IE versions you will need to adapt the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function load(url, callback) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
callback(req.responseXML);
};
req.send();
}
function transform(xml, xsl) {
load(
xml,
function(inputXml) {
load(
xsl,
function(xsltSheet) {
displayResult(inputXml, xsltSheet);
}
);
}
);
}
function displayResult(xmlInput, xsltSheet) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
document.getElementById('example').appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
document.getElementById("example").innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="transform('catalog.xml', 'catalog.xsl')">
<div id="example"></div>
</body>
</html>
Online at http://home.arcor.de/martin.honnen/xslt/test2015072001.html, works fine with current versions of IE, Firefox and Chrome on Windows 8.1.
If you want to start two asynchronous requests directly to load XML and XSLT then you need to do some more work to make sure you know when both documents have been loaded to process them, an example of that is at http://home.arcor.de/martin.honnen/xslt/test2015072101.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function makeRequest(url, loadedData, property, elementToAddResult) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
loadedData[property] = req.responseXML;
if (checkLoaded(loadedData)) {
displayResult(loadedData.xmlInput, loadedData.xsltSheet, elementToAddResult);
};
};
req.send();
}
function checkLoaded(loadedData) {
return loadedData.xmlInput != null && loadedData.xsltSheet != null;
}
function loadAndTransform(xml, xsl, elementToAddResult) {
var loadedData = { xmlInput: null, xsltSheet: null };
makeRequest(xml, loadedData, 'xmlInput', elementToAddResult);
makeRequest(xsl, loadedData, 'xsltSheet', elementToAddResult);
}
function displayResult(xmlInput, xsltSheet, elementToAddResult) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
elementToAddResult.appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
elementToAddResult.innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="loadAndTransform('catalog.xml', 'catalog.xsl', document.getElementById('example'));">
<div id="example"></div>
</body>
</html>

How to retrieve an element from an ajax call

I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}

add javascript get function to a href

I am very new to this
I have this link:
<a onclick = sendRequest('GET','room_chart.jsp') href=#>Show Chart</a>
but I need to generate dynamic address inside that link.
I created javascript:
<script language="javascript">
var selectedOption;
var ROOM;
var BUILDING;
function GetLink(){
selectedOption = document.getElementById("roomandbuildingid").options[e.selectedIndex].text; //getting selected option
ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim(); //parsing text
BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim(); //parsing text
return "'room_chart.jsp?room="+ROOM+"&building="+ BUILDING+"'"; //returning url
}
</script>
but when I paste the function into it- it does not work!
<a onclick = sendRequest('GET',GetLink()) href=#>Show Chart</a>
Now, after debug, I found out that actually it creates the proper srting, but somehow my function is not willing to accept it as URL! It is quite a paradox- it creates correct string- if I hardcode it into the code- it works! But dynamic links from variables - don't work!
please help!
see below:
my js file:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
// alert( document.URL );
// document.write (GetLink());
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
OK, the function was returning everything correctly, the parsing was not done right. I fixed it. JavaScript is hard for me to debug.

Categories

Resources