Getting a 404 error when when trying to run html page - javascript

I am trying to send over a string from PHP to a variable in JSON. But each time the page loads I get a 404 resource error for some reason. I don't understand what is happening and why I keep getting this error. I get the error after the webpage runs through the script part of the code. The way I check this out was using the dev kit in google chrome.
I'm running PHP through Microsoft IIS.
GettingFileInfo.php
<?php
//Calls the getFileInfoMainFunction
getFileInfoMainFunction();
//Function : sscaddir
//Parameters : $dir
//Returns : array
//Description : This function takes an array where we get rid of the dots
function sscandir($dir)
{
return array_values(array_diff(scandir($dir),array('..','.')));
}
function getFileInfoMainFunction(){
//variables
$implodedFilesEqual;
$toJson;
//C:\localwebiste\holmes-e-joesph-r
$fileDirectory=dirname(__FILE__);
//now we are in the MyFilesDirectory
$fileDirectory.="\MyFiles";
//store all the files in the filedirectory in an array
$files=sscandir($fileDirectory);
//The '|' delimter
//This is the string that we will send too the client side code.
$implodedFilesEqual=implode("|",$files);
//For testing purpose
print_r($files);
$toJson=json_encode($implodedFilesEqual);
echo ($implodedFilesEqual);
//Test.txt|test3.txt
}
?>
HTML page:
<html>
<head>
<title>Starting Page</title>
<link rel="stylesheet" href="StartPage.css" media="screen">
<script src="https://ajax.googleeapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jQuery.js"></script>
</head>
<body id="theTextEditorsBody">
<p id="demo"></p>
<h1>Text Editor</h1>
<hr>
<textarea id="textArea"></textarea>
<br>
<select>
<option>textFile1</option>
<option>textFile2</option>
<option>textFile3</option>
</select>
<p id="hello"></p>
</body>
jQuery.js:
const xmlhttp=new XMLHttpRequest();
xmlhttp.onload=function(){
const myObj=JSON.parse(this.responseText);
document.getElementById("demo").innerHTML=myObj.name;
}
xmlhttp.open("POST","GettingFileInfo.php");
xmlhttp.send();

Related

Google Apps Script: passing error into templated HTML

I have the following code:
code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Menu')
.addItem('Test', 'showTestForm')
.addToUi();
}
function showTestForm() {
var html = HtmlService.createHtmlOutputFromFile('TestForm');
SpreadsheetApp.getUi().showModalDialog(html, 'TEST');
}
function Test(formObject){
Logger.log("TEST")
var a = new Error( "Allready present "+ formObject);
a.error_code = 99;
Logger.log(JSON.stringify(a));
throw a;
}
TestForm.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<base target="_top">
<script>
function onFailure(error) {
var keys = Object.keys(error);
alert(JSON.stringify(keys));
alert(JSON.stringify(error.message));
alert(JSON.stringify(error.error_code));
}
function onSuccess() {
alert("Success");
}
</script>
</head>
<body>
<input type="submit" value="Save" onclick="google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).Test('1')" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
When I open TestForm from menu and press "Save" I've got following log from Logger:
[18-12-24 23:08:24:765 PST] TEST
[18-12-24 23:08:24:766 PST] {"message":"Allready present 1","error_code":99}
So I see, that error object have properties 'message' and 'error_code'. But in browser I've got following alerts:
["name"]
"Error: Allready present 1"
undefined
So I see, that recived error object has only one empty (i've checked) property "name". But if I but refer to the property "message, I've got string like in original object (but not the same). And it looks like that object haven't poperty "error_code".
What's the matter?
I thought you might like a complete working example as I know this stuff can be quite frustrating.
This a simple example templated HTML file that can be used as a dialog or a webapp. All it does is create a Google Doc file with todays date in the header and footer of each page and it puts the file into the same directory as the spreadsheet which contains the script. That's it. I use the Chrome Browser. I don't even care if my scripts won't run on another browser.
Here's the HTML: (FileName:'docwithdate.html')
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('resources') ?>
<?!= include('css') ?>
</head>
<body>
<?!= include('form') ?>
<?!= include('script') ?>
</body>
</html>
The Resources: (FileName: 'resources.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>
The CSS: (FileName: 'css.html')
<style>
body {background-color:#ffffff;}
input[type="button"]{padding:0 0 2px 0;}
</style>
The Form: (FileName: form.html) This is probably push the templating idea a little far.
<form id="myForm" onsubmit="event.preventDefault();processForm(this);" >
<input type="text" id="txt1" name="filename" />
<input id="btn" type="submit" value="Submit" />
</form>
The Javascript: [FileName: 'script.html')
<script>
function createFile(){
var name=document.getElementById('filename').value;
google.script.run
.withSuccessHandler(function(rObj){
var html='<br />Go To File:' + rObj.filename + '';
$(html).appendTo("body");
})
.createTemplatedGoogleDoc(name);
}
function getInputObject(obj) {//I'm probably doing something wrong here. But this is what I had to do to get the object with the properties that I desired. So if you have another way. Go for it.
var rObj={};
for(var i=0;i<Object.keys(obj).length;i++){
if(obj[i].type=="text"){
rObj[obj[i].name]=obj[i].value;
}
console.log('Object.keys(rObj): %s',Object.keys(rObj).join(', '));
}
return rObj;
}
function processForm(obj){
var fObj=getInputObject(obj);
var name=fObj.filename;
google.script.run
.withSuccessHandler(function(rObj){
document.getElementById("btn").disabled=true;
var html='<br />Go To File:' + rObj.filename + '';
$(html).appendTo("body");
})
.createTemplatedGoogleDoc(name);
}
console.log('My Code');
</script>
The Google Script: (FileName: Code.gs)
function onOpen(){
SpreadsheetApp.getUi().createMenu('My Menu')
.addItem("Open Templated Google Doc", 'showMyDialog')
.addToUi()
}
function createTemplatedGoogleDoc(name){
Logger.log(name);
var doc=DocumentApp.create(name);//Creates a google doc
var fldrs=DriveApp.getFileById(SpreadsheetApp.getActive().getId()).getParents();
while(fldrs.hasNext()){
var fldr=fldrs.next();
if(fldr.getName()=="Create Templated Google Doc App"){
var folder=fldr;
}
}
Drive.Files.update({"parents": [{"id": folder.getId()}]}, doc.getId());//puts doc file into same directory as the spreadsheet that contains the script
doc.addHeader().appendParagraph(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd, yyyy"));
doc.addFooter().appendParagraph(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd, yyyy"));
//doc.getBody().getChild(0).removeFromParent();
doc.saveAndClose()
var rObj={url:doc.getUrl(),filename:doc.getName()}
return rObj;
}
function showMyDialog(){
var ui=HtmlService.createTemplateFromFile('docwithdate').evaluate();
SpreadsheetApp.getUi().showModelessDialog(ui, 'My Doc with Date');
}
function doGet(){//if you want a web app this is helpful
return HtmlService.createTemplateFromFile('docwithdate').evaluate();
}
function include(filename){//this is the include that the template uses
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
It's a pretty simple script. I hope it helps you get a start.
In accordance with the proposal of #TheMaster it is necessary to do this:
code.gs
function Test(formObject){
var a = new Error( JSON.stringify({msg:"Allready present "+ formObject,code:99}));
throw a;
}
TestForm.html
// removing "Error: " from message string to get our json back
var json = error.message.replace("Error: ",'')
var msg = JSON.parse(json).msg;
var code = JSON.parse(json).code;
That is, we put json into the attribute message of the Error object, and then, by cutting our json, we parse it and get the necessary values.
This is not exactly the answer to the question, but a good way to solve the problem.

php ajax javascript/ecmascript html write to text file

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

How to load different html files in QUnit?

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
}
}

Unable to read text file in Javascript

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();

parsing a xml file using javascript does not givethe required result

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?

Categories