I'm not overly experienced with the aforementioned technologies, but need to resolve the issues i'm experiencing with the POST function.
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<meta charset='UTF-8'>
<script src='lib/ajaxget.js'></script>
<script src='lib/ajaxput.js'></script>
</head>
<body>
<h1>blah</h1>
<div>AJAX uploads go here.</div>
<div id="grabphpdiv"> AJAX uploads from PHP go here.</div>
<br>
<textarea id="comment" rows="5" cols="40"></textarea>
<br>
<button id="put">put</button>
<br>
<br>
<button id="get">get</button>
<script src='dyn.js'></script>
</body>
</html>
The JS 'GET' function is working, so here's the POST that doesn't work (no errors in the console) the text file doesn't update though...
function AjaxPut(URL, callback)
{ var ajaxObj = new XMLHttpRequest();
ajaxObj.open("POST", URL, true);
ajaxObj.onreadystatechange = function()
{ if (ajaxObj.status == 200)
if (ajaxObj.readyState == 4)
callback(ajaxObj.responseText);
};
ajaxObj.send("somestuff");
};
And the PHP for the post (though titled PUT here)
<?php
$jothandle = fopen("jots.txt","w");
fwrite($jothandle,$_REQUEST['line']);
Lastly, here's the JavaScript that's entitled 'dyn.js' at the bottom of the HTML. (though for brevity, i've only pasted in the POST section.
var y = document.getElementById("put");
y.addEventListener("click", runapi1);
y.addEventListener("click", grabphp1);
function runapi1()
{ AjaxPut('api/put.php', grabphp1);}
function grabphp1(response)
{ document.getElementById('grabphpdiv').innerHTML = response; }
Any help or pointers would be very much appreciated! thanks!
It looks like you aren't sending a parameter called line from your JS, but you are expecting one in your PHP code. Try sending this instead: line=somestuff e.g.
ajaxObj.send("line=somestuff");
Send POST data using XMLHttpRequest
Related
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id="textetrad" rows="5"></textarea>
<textarea id="translated-text" rows="5"></textarea>
<button id="run-translation" onclick="runTranslation();">Translate</button>
<script>
function runTranslation() {
var data = document.getElementById("textetrad").value;
var trad = LanguageApp.translate(data, 'en', 'es');
document.getElementById("translated-text").value = trad;
}
</script>
</body>
</html>
Hello, I am creating a bar lateral and I have a problem. I would like to create a textarea where we insert what we want and it is translated in another textarea. I have tried different methods like LanguageApp.translate(data , 'en', 'es') but I can't get this function to work in the HTML code.
So already is what I want possible without using an API?
If yes, should I do it only in the HTML code or should I make the HMTL code and the .gs communicate?
And then how do I transmit the translation from the gs code to the HTML?
I tried and made it work on apps script using LanguageApp
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<script type="text/javascript">
function runTranslation() {
google.script.run.withSuccessHandler(onSuccess).translate(document.getElementById('textetrad').value);
}
function onSuccess(data) {
document.getElementById('translated-text').value = data;
}
</script>
<body>
<textarea id="textetrad" rows="5"></textarea>
<textarea id="translated-text" rows="5"></textarea>
<button id="run-translation" onclick="runTranslation();">Translate</button>
</body>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function translate(textValue){
// automatically identify the language, then translate to spanish
return LanguageApp.translate(textValue, '', 'es');
}
Process:
upon onclick, execute runTranslation.
when translate function (in Code.gs) runs with no issue, proceed with onSuccess
passing the translated data, assign it to the other element
Output:
Reference:
HTML Service: Communicate with Server Functions
So, i've been experimenting with de google apps script lately. So far so good, but i ran into a problem that's drivin me out: I have a button in a spreadsheet that calls a sidebar menu with a function in scripts
macros.gs
function sbCases() {
var Form = HtmlService.createTemplateFromFile("Cases");
var ShowForm = Form.evaluate();
ShowForm.setTitle("ASS-CAD - Cases manager system").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showSidebar(ShowForm);
the html file I call with this function works just fine, but I'd like to call a second form, also trough an html file to manage the spreadsheet data. So i've added this function to the .gs file (and started a new html file):
function NovoCasoMSE(){
var Form = HtmlService.createTemplateFromFile("NewCase");
var ShowForm = Form.evaluate();
ShowForm.setTitle("New Case").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showModalDialog(ShowForm, "New Case");
}
but when I try to call it from a button in the first html file, nothing happens at clicking the button (checked the log and the function the button should call isn't being executed.
Follow the code (the html is full of stuff, like the buttons and everything)("btn" is the ID for a button working on the html file):
<script>
document.getElementById("btn").addEventListener("click", NewCase);
function NewCase(){
google.script.run.NewCase()
}
</script>
I'm learning c in college but have very little experience in javascript ou google script, so I'm pretty sure I've done something really wrong. Thanks for any help in advance. :)
You can try something like this:
Run showTSidebar to get things rolling and then click the button.
ag1.gs:
function loadForm() {
var html='<form><input type="text" name="name1"/><input type="button" value="Click" onClick="process(this.parentNode);" /></form>';
return html;
}
function showTSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createTemplateFromFile('ah4').evaluate());
}
function processForm(obj) {
SpreadsheetApp.getUi().alert('name1: ' + obj.name1);
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
ah4.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('sbresrc') ?>
</head>
<body>
<div id="form"></div>
<input type="button" value="Load Form" onClick="loadForm();" />
<?!= include('ah6') ?>
</body>
</html>
ah6.html:
<script>
function loadForm() {
google.script.run
.withSuccessHandler(function(html){
$('#form').html(html);
$('#form').css('display','block');
})
.loadForm();
}
function process(obj) {
google.script.run.processForm(obj);
}
</script>
sbresrc.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
animation:
I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}
I have a local text file present in the location /home/myname/Desktop/iot/public/sensordata.txt. This file has to be read in JavaScript when a button is clicked on a web page. My code is given below:
<html>
<head>
<title>Humidity</title>
</head>
<body>
<h3>Humidity page</h3>
<table>
<tr>
<td>
<button type="button" onclick="humidgraph('public/sensordata.txt','chartContainer')">View live humidity data</button>
</td>
</tr>
</table>
<p><div id="chartContainer" style="height: 300px;width= 100%;"></div></p>
<script type="text/javascript">
function humidgraph(datasource,divid){
var i=0;
var xVal,yVal;
var humidity=[],time=[],dps=[];
var fileread=false;
var obj=document.getElementById(divid);
if(window.XMLHttpRequest){
fileread=new XMLHttpRequest();
}else if(window.ActiveXObject){
fileread=new ActiveXObject("Microsoft.XMLHTTP");
}
if(fileread){
fileread.open("GET",datasource);
document.getElementById("chartContainer").innerHTML=fileread.responseText;
}
fileread.onreadystatechange=function(){
if((fileread.readyState===4 || fileread.readyState===0) && fileread.status===200){
var text=fileread.responseText;
text.split(/\n/).forEach(function(item){
humidity.push(Number(item.match(/Humidity(.\d+[.]\d+)/)[1]));
});
text.split(/\n/).forEach(function(item){
time.push(Number(item.match(/time(.\d+[.]\d+)/)[1]));
});
}
}
while(i<time.length){
xVal=time[i];
yVal=humidity[i];
dps.push({x: xVal,y: yVal});
i++;
}
}
</script>
</body>
</html>
However, no data is being printed on the html page, even though innerHTML is being used. Is there something wrong with my file path? Please help.
You need to run a webserver and make the get request to a URI on that server, rather than making the get request to a file (you get a "cross origin requests" error).
Then change:
humidgraph('public/sensordata.txt','chartContainer')
to read something like:
humidgraph('http://localhost/public/sensordata.txt','chartContainer')
and the initial request page needs to be loaded from that server as well.
Additionally you should do your request in the below order:
fileread.onreadystatechange=function (){
...
};
...
fileread.open("GET", datasource);
fileread.send();
I am trying to parse a XML-file using java-script. Actually, I read many tutorials to find out how to parse the data from the XML-file correctly, and I found that I am on the right way.
Concerning the loadXMLDoc(dname) function, I passed the path of the XML-file to loadXMLDoc function as follows:
var dname = "D:\files\files\Schriftsteller.xml";
function loadXMLDoc(dname)
But still the parsing does not give me the desired result, I want to display the name in the following tag
<name>Jane Austin</name>
but the web browser does not display it, I am using Chrome.
Please, (1) Let me know where my mistake is? (2)what extension the parser file should be saved under(.HTML/.js)
Please find below the XML-file and the java-script file
XML file:
<?xml version="1.0" ?>
<Schriftsteller>
<Englischsprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</Englischsprache>
</Schriftsteller>
JavaScript File.html(Parser):
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="readXML.css" type="text/css">
<title>Read First Child</title>
<!-- <xml ID="Schriftsteller" SRC="D:\files\files\Schriftsteller.xml"></xml> -->
<script language="JavaScript">
var dname = "D:\files\files\Schriftsteller.xml";
function loadXMLDoc(dname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",dname,false);
xmlDoc.send();
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige;
myXML = document.all(dname).XMLDocumentalert(dname);
SchriftstellerKnoten = myXML.documentElement;
SpracheKnoten = SchriftstellerKnoten.firstChild;
DichtungKnoten = SpracheKnoten.firstChild;
FuellerKnoten = DichtungKnoten.firstChild;
NameNode = FuellerKnoten.firstChild;
Anzeige = NameNode.firstChild.nodeValue;
document.write(Anzeige);
}
</script>
</head>
<body onload="loadXMLDoc(dname)">
<span ID="blueBack">Read firstChild</span>
<div>
<form name="show">
<input type=text name="me">
<input type="button" value="Display Writer"
onClick="findWriter()">
</form>
</div>
</body>
First your XML-Document has to be well-formed.
So for every tag you open add another tag to close it (like you do with the name-tag). The closing tag has to be same as the opening, except for a / in the beginning
Also you have to watch the case (well-formed XML is case-sensitive). The tag
<EnglischSprache> is different from <Englischsprache>
Try it like this:
<?xml version="1.0"?>
<Schriftsteller>
<EnglischSprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</EnglischSprache>
</Schriftsteller>
Then in the JS-File, maybe you should try calling the function loadXMLDoc.
Looks like you're just defining it.
Try it like this:
<body onload="loadXMLDoc(dname)">
Better now?