How to save XML GET response to file in PhantomJS - javascript

I want to save a GET response to a file. This is my code:
function(){
var page=require('webpage').create();
var callback=function(status){
if (status=='success'){
page.render('pic1.png');
var fs = require('fs');
fs.write('reppo.xml',page.content,'w')
console.log('Got report...');
}else{
console.log('Failed to load.');
}
};
var url = "https://10.84.163.146/event_stream/events_in_xml?events=137,138&arow=902&noxsl=y&nonmal=y";
page.open(url,callback);
},
I expect a XML document as answer. When i put the link directly in my browser, everything works fine but when i execute the script i get a file that contains the following code:
<html xmlns="http://www.w3.org/1999/xhtml"><body><parsererror style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black"><h3>This page contains the following errors:</h3><div style="font-family:monospace;font-size:12px">error on line 1 at column 0: Encoding error</div><h3>Below is a rendering of the page up to the first error.</h3></parsererror></body></html>
Any ideas?

try changing your user agent. I know in PHP if I don't do this some websites block access. Add this code right after initing webpage.
page.settings.userAgent = 'Chrome/28.0.1500.71';

Related

Pass data of dropped files inside a div to another page

document.getElementById('drag_drop').ondrop = function(event)
{
event.preventDefault();
var form_data = new FormData();
var drop_files = event.dataTransfer.files;
for(var count = 0; count < drop_files.length; count++)
form_data.append("images[]", drop_files[count]);
var ajax_request = new XMLHttpRequest();
ajax_request.open("post", "upload.php");
ajax_request.send(form_data);
}
#drag_drop{
background-color : #f9f9f9;
border : #ccc 4px dashed;
line-height : 250px;
padding : 12px;
font-size : 24px;
text-align : center;
}
<div id="drag_drop">Drag & Drop File Here</div>
This code allow you to upload files using the "drag and drop" function: I drop the files in the apposite div (#drag_drop) and with JS I create a POST request to the PHP file that will upload the files...
What I want to do is that as soon as the user drops the files redirect to ANOTHER html page containing the script and then send the request to the PHP file.
I have no idea how not to lose the data of the files dropped inside the div during the page change (maybe inserting form_data/drop_files in a localstorage item... (?)).
NO JQUERY.
I have not tested this, but when you upload a file to your browser, you can use createObjectURL() to create a local URL where your file resides.
You can save this URL in the localStorage (or similar) and read it on the other page again.
const selectedFile = document.getElementById('input').files[0];
const objectURL = window.URL.createObjectURL(selectedFile);
localStorage.setItem('UPLOADED_FILE', objectURL);
// ... change page
const retrievedUrl = localStorage.getItem('UPLOADED_FILE');

How to sync printing of characters with sound?

I need to emulate what an old manual typewriter does when printing what is being typed on a web page. I want to develop JavaScript functions to pass it a string, and it would print out each character with a delay, and the sound file synced with each letter.
I'm new to JavaScript. What is the preferred method to do this? Should I be looking at jQuery for this? Or is this something simple to do?
I've seen problems with sound files being triggered like this on some web browsers, is there an audio file format which is best for this sort of thing?
I've found this, but the problem is, it doesn't work on all web browsers:
https://rawgit.com/mehaase/js-typewriter/master/example3-typewriter/index.html
You can try something like this:
// The delay between each keystroke
var delay = 300;
// The typewriter sound file url
var clickURL = "https://cdn.rawgit.com/halimb/res/6ffa798d/typewriter.wav";
// Get a reference to the container div
var container = document.getElementById("container");
var sampleString = "Hello world!";
//get a reference to the start button and typewrite onclick
var start = document.getElementById("btn");
start.onclick = function() { typewrite( sampleString ); };
function typewrite( str ) {
var i = 0;
container.innerHTML = "";
type();
function type() {
var click = new Audio( clickURL );
// This is triggered when the browser has enough of the file to play through
click.oncanplaythrough = function() {
click.play();
// Add the character to the container div
container.innerHTML += str[i];
i++;
if(i < str.length) {
window.setTimeout(type, delay);
}
}
}
}
* {
font-family: Courier;
font-size: 32px;
}
.btn {
display: inline-block;
border: 1px solid black;
border-radius: 5px;
padding: 10px;
cursor: pointer;
margin: 10px;
}
<div class="btn" id="btn">Start</div>
<div id="container"></div>
Update: on Safari. It seems the audio has to be triggered by a user event (e.g: onclick..), so I added a button, and made the typewriter start onclick.
The downside is that there's no way to pre-load the audio file, Safari make a server request and downloads the audio each time it is played. the only (dirty) way I could think of to overcome this is to provide a data URI instead of the audioURL.. you can try that if the playback speed really matters (this can be helpful: https://www.ibm.com/developerworks/library/wa-ioshtml5/)

How to dynamically create downloadable link from user uploaded files (disregarding file types) without calling server?

HTML:
<input id="browse" type="file" multiple>
<div id="preview"></div>
Javascript:
var elBrowse = document.getElementById("browse");
var elPreview = document.getElementById("preview");
function readFile(file) {
//Create downloadable link and generate DOM elements.
var fileName = file.name;
elPreview.insertAdjacentHTML("beforeend", "<a>" + fileName + '</a>');
elPreview.insertAdjacentHTML("beforeend", "<a>Delete</a><br>");
}
elBrowse.addEventListener("change", function () {
var files = this.files;
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for (var i = 0; i < files.length; i++) {
var file = files[i];
readFile(file);
}
}
});
I am facing a new requirement, but I don't have much experience in Javascript. Basically, I want users to be able to upload files by clicking the browse button and displays the files name with downloadable link. User can upload files of any type and be able to download the files back.
The whole process MUST not trigger the backend server and everything has to be done in javascript or JQuery. Could anyone help please? Thank you.
System and User interaction:
User uploads a file
System saves the file in javascript and displays the file name with downloadable link.
User delete it.
System removes it from DOM and javascript
User can repeat step 1-4. The whole process does not trigger the server at all.
Eventually, user submits all the files to the server by clicking somewhere else (This step is out of the scope of this post)
If you are using a modern browser then you can utilize the HTML5 FileReader. I've used it, but found an example more suited to your question here.
You can use the FileReader to read the files on the client side, and store in sessionStorage, localStorage, or even a variable. But the one caveat is that you'll probably run out of RAM because JavaScript's not really designed for retaining large BLOBs in RAM.
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
min-height: 300px;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
img {
max-width: 100%;
}
#fileDisplayArea {
margin-top: 2em;
width: 100%;
overflow-x: auto;
}
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>

Message DIV Issues

I have the following javascript it pops up a message on the screen, but always over the top of the previous messageDiv if it hasn't been removed yet.
I am trying to figure out how to get the messageDiv to either push the previous div down until it disappears and then takes the previous MessageDiv's place, or show up just below the current one on the page moving down just below the previous one as new ones appear.
function pushDev(){
$.post( "#cgi.SCRIPT_NAME#", {fileId: "#fileIdIn#", action: "migrateFileDev"}, function(data){
$("body").prepend("<div class='pageMessage' id='messageDiv'>" + data + "</div>");
setTimeout(function(){$('#messageDiv').remove()}, 6000);
});
}
function savePage(){
var code = editor.getValue();
$.post( "#cgi.SCRIPT_NAME#", {fileIdIn: "#fileIdIn#", filePath: "#path#", action: "savePage", editText: code }, function(data){
$("body").prepend("<div class='pageMessage' id='messageDiv'>Saved</div>");
setTimeout(function(){$('#messageDiv').remove()}, 6000);
});
}
.pageMessage{
/*position:fixed;*/
/*top: 15%;*/
/*right: 8%;*/
background-color: #f5f5f5;
opacity: 0.9;
color: #FFF;
font-size: 18px;
text-align:center;
padding: 8px;
width: auto;
height:auto;
border:solid;
border-color: #00A3DD;
border-width: 3px;
z-index: 1000;
border-radius: 8px;
}
I think you are running into a problem because you have multiple elements with the same ID and when your setTimeout callback executes, it removes the newest message rather than the oldest one. Only one element with a given ID is allowed in HTML. You need to figure out a different way of finding the div that should be deleted for the particular timeout, for example (I got rid of the irrelevant AJAX code):
function pushDev(){
var messageDiv = $("<div class='pageMessage'>Data</div>")
$("body").prepend(messageDiv);
setTimeout(function(){messageDiv.remove()}, 6000);
}
function savePage(){
var messageDiv = $("<div class='pageMessage'>Saved</div>")
$("body").prepend(messageDiv);
setTimeout(function(){messageDiv.remove()}, 6000);
}
JSFiddle here.

changing CSS elements with javascript for same element id in multiple places

Okay so im pretty new to html/javascript/css through some tutorials and this site it's coming along. I am attempting to display a button which i use css to overlay with an image when the button is clicked I call a javascript function to send some info to my server as well as replace the button which was clicked with a new button and image overlay. here is the code snippets responsible for this (I'm basically just toggling the visibility on the buttons back and forth):
<style type = 'text/css'>
input.btn_follow {
position: absolute;
right: 2px;
top: 2px;
background-image: url(http://icons.iconarchive.com/icons/icojam/onebit/48/star-100-icon.png); /* 16px x 16px */
}
input.btn_unfollow {
visibility: hidden;
position: absolute;
right: 2px;
top: 2px;
background-image: url(http://gologic.com/imagesOld/checkmark%20-%20small.png);
}
</style>
</head><body>
<script type='text/javascript'>
function follow(series, status) {
var xhReq = new XMLHttpRequest();
var request = "follow.php?series="+series+"&status="+status
xhReq.open("GET", request, false);
xhReq.send(null);
var response = xhReq.responseText;
var IDyes = "follow_"+series
var IDno = "unfollow_"+series
if (response == 1){
document.getElementById(IDyes).style.visibility='hidden'
document.getElementById(IDno).style.visibility='visible'
}
else if (response == 0){
document.getElementById(IDyes).style.visibility='visible'
document.getElementById(IDno).style.visibility='hidden'
}
else if (response == -1){
alert("you must first login to use the follow request"); // now following show
}
}
</script>
So all of this kind of works, however for some element ID's they appear multiple times on the same html page. If this is the case only the first instance of the element is the visibility is changed and not for the rest. why is this if they have the same id ? how can I fix this? here is a link to see this in action on my web page to make this more clear http://ec2-54-234-192-222.compute-1.amazonaws.com/home.php (the button's in question are the stars)
any help would be greatly appreciated (also if there is a cleaner way scraping what i Have i'd be open to as already starting to resemble spaghetti!)
thanks -brendan
So as in the comments above Id's should only appear once per page! I'm blaming this on being a newb thanks to #Jeff shaver for clarrifying this

Categories