Read text file and display in web page [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am seeking some help. I am very new to programming and I’m working on a new project.
The objective is to display the contents of a plain text file in a web page.
The text file (named title.txt) and has a single line of text
The text file is located on my server
The text content changes every three minutes or so.
I wish to read this file and display its content in a web page
The web browser is to automatically re-read the file every three minutes or so.
I have looked at a number of websites to achieve this, however i am confused by the options available. I read that Jquery/ajax can perform this task.
Can anyone help me by providing some example code.
Many thanks
Colin

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<Body>
<p><center>Current Track: <span id="trackinfo">No track information available at this time</span></p></center>
<script>
function radioTitle() {
var url = 'http://XXX.no-ip.org:8000/tracktitle.txt';
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) {
$("#trackinfo").html(data)
},
error: function(e) {
console.log(e.message);
}
});
}
$(document).ready(function(){
setTimeout(function(){radioTitle();}, 2000);
setInterval(function(){radioTitle();}, 15000);
});
</script>
</body>
</head>
</html>

var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
readTextFile("your file path");
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}

Related

Re-write $.ajax request as JavaScript XMLHttpRequest [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to get better at writing my code in JavaScript and not using jQuery. I've got an $.ajax request which i'm trying to rewrite as an XMLHttpRequest, but getting errors "POST http://localhost:3000/wp-admin/admin-ajax.php 400 (Bad Request)".
The jQuery version works fine, but the JS version doesn't. I get the same error from the jQuery version if I remove data: filter.serialize(), so I feel the issue lies here as there isn't an equivalent version in the JS request, but i'm unsure how to write/add this into it.
If anyone can point me in the right direction that would be great : )
/** Working jQuery filter */
jQuery(function($) {
$("#filter").change(function(e) {
e.preventDefault();
var filter = $(this);
$.ajax({
url: WP.ajax,
data: filter.serialize(),
type: "POST",
beforeSend: function(xhr) {
$("#response").append("Loading...");
},
success: function(data) {
$("#response").html(data);
}
});
return false;
});
});
/** NOT working JS filter */
var af = new XMLHttpRequest();
document.getElementById("filter").addEventListener("change", function(e) {
e.preventDefault();
document.getElementById("filter").value = this.value;
af.onload = function() {
if (af.status === 200) {
document.getElementById("response").innerHTML = af.responseText;
console.log(af.responseText);
}
};
af.open("POST", WP.ajax);
af.send();
});
I've worked it out and got the data sending. For reference the working code is below:
var articleFilter = new XMLHttpRequest();
var filter = document.getElementById("filter");
filter.addEventListener("change", function(e) {
e.preventDefault();
filter.value = this.value;
articleFilter.onload = function() {
if (articleFilter.status === 200) {
document.getElementById("response").innerHTML = articleFilter.responseText;
}
};
articleFilter.open("POST", WP.ajax, true);
var formData = new FormData(filter);
articleFilter.send(formData);
}); // END

jQuery click function only called once [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
As the title says, I have some code that only fires the click event once. Can you guys take a look?
UPDATE:
I have edited the code to show the whole function. Im making a plugin for jQuery. Anyway, the point is that the code DOES WORK but the click function of a.click() ets fired only once, removing one filter only.
addFilterProcess: function ()
{
var $this = this;
var select_filters = this.select_filters;
var selected_filter = select_filters.val();
if (selected_filter != 0)
{
if (this.active_filters.length == 0)
{
this.active_filters.push(selected_filter);
this.used_filters.append(this.template_show_filter(this.options.available_filters[selected_filter], selected_filter));
var filter = this.used_filters.find('#filter-'+selected_filter);
var a = filter.find('a');
a.click(function () {
$this.removeFilter(a.attr('filter'));
});
this.btn_apply_filters.show();
this.btn_cancel_filters.show();
this.btn_apply_filters.on('click', function () {
$this.applyFilters();
});
this.btn_cancel_filters.on('click', function () {
$this.cancelFilters();
});
/*
Reset the select, to show the first option
*/
select_filters.val(0);
}
else
{
if (this.active_filters.indexOf(selected_filter) === -1)
{
this.active_filters.push(selected_filter);
this.used_filters.append(this.template_show_filter(this.options.available_filters[selected_filter], selected_filter));
/*
Reset the select, to show the first option
*/
select_filters.val(0);
}
}
}
},
Try
$(this).removeFilter(a.attr('filter'));

If else with ajax call wont work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
anyone can tell me why this wont work? It does work when i dont use a if else statement so im a bit stunned atm, i am using a html5 player where the play/pause button toggles, it needs to include the ajax watching when playing and stop watching when paused. thnx
<script>
var test = 0;
if (test == 0) {
$("#play").click(function(){
$.ajax({
url: "start_watching.php",
success: function(result){
$("#fix").html(result);
}
});
)};
test = 1;
} else if (test == 1) {
$("#play").click(function(){
$.ajax({
url: "stop_watching.php",
success: function(result){
$("#fix").html(result);
}
});
)};
test = 2;
}
</script>
Here's a really verbose example of how to solve the logic, with the conditions inside the event handler
var test = 0,
url;
$("#play").click(function(){
if (test === 0) {
url = "start_watching.php";
test = 1;
} else {
url = "stop_watching.php";
test = 0;
}
$.ajax({
url : url,
success : function(result){
$("#fix").html(result);
}
});
});

WebWorker - Ajax call - error [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 7 years ago.
I am trying to make an AJAX call to ajax.htm file. using web-worker. If it works fine, the data must keep populating at the given interval.
I dont get an error, and the get message seems to be working, but the data is not being populated on page. The message posted by the worker.js is not being listened to in the main page. Here is the code.
My webWorker.html file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Worker Sample</title>
<script type="text/javascript">
var worker = new Worker('worker.js');
// console.log(worker);
document.addEventListener("DOMContentLoaded",function(){
var result = document.querySelector('#result');
// console.log(result);
worker.addEventListener('message', function (event) {
console.log(event.data);
createElement('li', result,'',JSON.parse(event.data));
});
worker.addEventListener('error', function(err){
console.log("There was a problem",err);
});
worker.postMessage('start');
});
function createElement(elementType, parent, className, innerHTML, custom) {
var element = document.createElement(elementType);
if (parent) parent.appendChild(element);
if (className) element.className = className;
if (innerHTML) element.innerHTML = innerHTML;
if (typeof custom !== 'undefined') {
for (var prop in custom) {
element.setAttribute(prop, custom[prop]);
}
}
return element;
}
</script>
</head>
<body>
<div>
<ul id="result">Result</ul>
</div>
</body>
<html>
my worker.js is as follows:
/**
* Created by lakshmi on 7/22/15.
*/
self.addEventListener('message', function (e) {
if(e.data === 'start'){
setInterval(function () {
getData()
}, 1000);
}
function getData() {
var xhr = new XMLHttpRequest();
xhr.open('GET','ajaxcontent.htm');
xhr.withCredentials = true;
// xhr.setRequestHeader("Content-Type", "text/event-stream");
xhr.addEventListener('readyStateChange',function(){
if(xhr.readyState === 4){
self.postMessage(xhr.responseText);
}
});
xhr.send();
}
});
ajaxcontent.htm
content from external page
CORS error means, that you are doing request to other domain, and other domain did not allow cross domain request.Try to do request to your domain.Other domain can allow some headers or some request method types (POST,DELETE,GET,PUT), can allow access from all domains or from some domains.
If you are disagree with my answer, explain why.

hide certain content based of an event [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I cannot find the right solution how hide a certain content on new part of page generated from PHP. (I am new in javascript)
I have a page, which loads new content below the actual, if a visitor scrolling down (like on Facebook.)
Each time, when a new content will displayed, I want run a function, which will hide certain content on the page.
Here is the code which loads new content. This works great.
(function() {
var $loadMore = $('.load-more').first();
if (!$loadMore.get(0)) {
return;
}
var timeout;
var $loadMoreLink = $loadMore.children('a'),
$list = $loadMore.prev('ul');
$loadMoreLink.on('click', function(event) {
event.preventDefault();
getMore();
});
function checkForMore() {
if (($window.scrollTop() + $window.height()) > ($list.offset().top + $list.height())) {
getMore();
}
}
function getMore() {
if (!$loadMoreLink.is(':visible')) {
return;
}
$loadMoreLink.attr('hidden', true);
$.get($loadMoreLink.attr('href'), function(response) {
$list.append(response);
var moreUrl = $list.children().last().data('more-url');
if (moreUrl) {
$loadMoreLink.attr('href', moreUrl);
$loadMoreLink.removeAttr('hidden');
}
else {
$loadMore.attr('hidden', true);
}
console.log(moreUrl)
});
}
$window.on('scroll', function() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(checkForMore, 50);
});
checkForMore();
})();
Here is my code, with help of which I want to hide certain content. That does not work :(. I have tried really much, and spent many days on that.
var hideUnity = document.getElementsByClassName("load-more");
for (var i = 0; i < hideUnity.length, i++) {
hideUnity[i].addEventListener("click", function() {
if (something && something) {
$(document).ready(function(){
$("li.unity").hide();
});
}
});
}
Link to loading file at page
<div class="load-more">
Load more
</div>
Can someone help me, please? :). Thanks.
I don't know if there is a reason to mix native js and jQuery, but you can do your function easily using the framework:
$(function(){
$(".load-more").on('click', function(){
// now $(this) represents clicked object while $('.load-more') still represents all elements with provided class
if( whateveryouwant ){
$("li.unity").hide();
}
});
});
Edit
If you need to use a delegated event, just replace
$(".load-more").on('click', function(){....
by
$(document).on('click', '.load-more', function(){....

Categories

Resources