Read input from a file and alert it - javascript

I want to read as input from a local file using Javascript and handle it, say alert the contents using Javascript.
Eg -
My page should read data from "hello.txt" which contains a line - Stack. So, my page should alert that line on the web-page.
I found similar questions on this site and tried them, but I'm not able to implement correctly.
function read(textfile)
{
var xhr=new XMLHttpRequest;
xhr.open('GET',textFile);
xhr.onload=show;
xhr.send()
}
Some suggestions were to use Ajax, but I don't know that language. Can't it be done using Javascript only?

You can do it with jQuery and ajax like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '/hello.txt',
type:'GET',
success: function(m){
alert(m);
}
});
});
</script>

Related

How can I make an AJAX application similar to nodebb?

I am very new to ajax and am really struggling. My end goal is to make a forum software like nodebb. I've already made a php forum but decided not to use it because it just seemed old unlike faster looking forums like nodebb. What I'm trying to understand is how to make multiple tabs that display different information each but keep the same data for the header. I understand this is probably a very simple thing to do, but currently I am unable to accomplish this.
https://dogecraft.net is a great example of what I'm trying to accomplish.
If you click on the different tabs, it loads information in each one. I tried this but I had trouble with the url. When I reloaded, it simply just loaded my new file and that's not what I want.
(Yes, I am using a local jquery file. Jquery isn't the issue.)
I've tried w3schools but didn't find really helpful information
I've also tried many other websites.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$( "#one" ).click(function(){
$("#div1").load("/one/").hide().fadeIn();
window.history.pushState("object or string", "Title", "/one/");
});
});
$(document).ready(function(){
$( "#two" ).click(function(){
$("#div1").load("two.html").hide().fadeIn();
});
});
</script>
</head>
<body>
<button id='one'>Page one</button> <button id='two'>Page two</button>
<h2>This text never changes :)</h2>
<div id="div1"></div>
</body>
</html>
I would like to have a homepage 'index.html/php'
I need a button to load one page of content (one.html/php) and then another button that loads another page of content (two.html/php).
On refresh, I would like it to keep the same content that was on the homepage including the buttons in the header.
You could make an Ajax call to your html/php to retrieve the html code and then inject the content on your div. Here is an example:
$(document).ready(function() {
$("#one").click(function() {
$.ajax({
url : 'http://myserver.com/myhtmlpage.html',
success : function(html) {
$("#div1").html(html);
}
});
});
$("#two").click(function() {
$.ajax({
url : 'http://myserver.com/myphppage.php',
success : function(html) {
$("#div1").html(html);
}
});
});
});
When you click a button, an ajax call is made, and if succesful, the success function will be called. The first parameter has the html code of the webpage you requested. Then you can use the html function of jQuery you can inject it on your div.
A couple of tips:
You might want to use only one onready function, no need to declare it several times
You might consider returning a json object with the data instead of a php page. This will be useful later on if you consider using a framework such as Angular or Vue. If you can generate a JSON file on your php such as this:
{
"name": "John"
}
Then you could do something like this:
$("#two").click(function() {
$.getJSON({
url : 'http://http://myserver.com/myphppagethatservesjson.php',
success : function(json) {
$("#div1").html("<h1>My name is " + json.name + "</h1>");
}
});
});
Then it will render "My name is John".
This could be improved a lot,but I hope it could help you a bit.

PHP Output Not Appearing in HTML

I have made some code to post the output of a PHP file showing the music I have been recently listening to on Spotify.
The HTML, CSS and JS (for the spotify.php file) are included in this fiddle.
The JS within my index.php file is:
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: 'https://theobearman.com/cv/modules/spotify.php',
data: {
request: 'true'
},
success: function(reply) {
$('.now-playing').html("" + reply + "");
}
});
}
window.onload = get_spotify;
</script>
My issue is that the output of the .php file is not showing up under the 'Music' header on my website.
This was working a few days ago, so I'm not sure why it is not working now.
Thanks in advance for any help,
Theo.
Try
$(document).ready(function() {
get_spotify();
});
instead of window.onload = get_spotify, which may run before the element is rendered on the page.
Try using a $(document).ready() to call your function instead of window.onload = ... this ensures that jQuery has correctly been loaded.
Example: $(document).ready(get_spotify);
I visited your site and everythings seems to be fine, only problem is that your function is not gettng called, I tried it from console and works perfectly
After having a look at your website code I found the problem.
You can have only one window.onload in one page but you have two of them so that's why it is not working.
Here is code of your first window.onload, put the get_spotify in here:
window.onload = function() {
get_spotify();//INSERT HERE
var elevator = new Elevator({
element: document.querySelector('.elevator-button'),
mainAudio: 'https://www.theobearman.com/cv/music/elevator-music.mp3',
endAudio: 'https://www.theobearman.com/cv/music/ding.mp3'
});
And also put get_spotify function body and prototype above this onload call.

Multiply Jquery and JqueryUI objects conflict? (php)

I am trying to put a script together that works with a Jquery object and a Jquery slider that also works with JqueryUI. I'm trying to figure out howto put it all together in a webpage (php) but trying to put just the slider in my webpage breaks both the functions and they don't work properly anymore.
Does anybody has an idea of what i am missing here and how the script fails to work properly?
NOTE REMOVING V1.9 OR V1.3 DOESNT MATTER CAUSE THE SCRIPT STILL WORKS 50%, EITHER THE SLIDER DOESNT WORK OR THE AJAX CALLS IN SCRIPT.JS
*first load all scripts and styles.
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.js"></script>
<script src="/shop/templates/Euphoria-Art/js/jquery.limitslider.js"></script>
<script type="text/javascript" src="/shop/templates/Euphoria-Art/js/script.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/themes/sunny/jquery-ui.css" rel="stylesheet" type="text/css"/>
SCRIPT.JS - There are 4 of these objects
$(document).ready(function() {
var form = $('#formB'); // form
var submit = $('#submitB'); // submit button
var alert = $('.pageB'); // div for show page
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '********/offertebeginC.php', // form action url
type: 'post', // form submit method get/post
dataType: 'json', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
},
success: function(result) {
if(result.error){
alert.html(result.html).fadeIn();
console.log(e)
}else{
alert.html(result.html).fadeIn();
form.trigger('reset');
}
}
});
});
});
If you must include multiple versions of jQuery, for instance using a plugin which depends on an earlier version, you'll want to use $.noConflict().
Take a look at the docs here, and a bit of a tutorial here

Why won't my links trigger jQuery.click events?

So, I'm dabbling in some jQuery today, and I come across an issue. I have a page that has a number of links in the following format:
<a class="a_link" id="a_id<#>" href="#">Click me</a>
Where <#> is a number generated in a for loop in the PHP that runs the page. At the top of the page, I have a script tag linking to the Google CDN for jQuery 1.7.2 minimized, and a div with id of "form_map". After all the links have been displayed, I have the following script:
<script type="text/css">
$(document).ready(function(){
$('.a_link').click(function(){
var c_id = $(this).attr('id');
var task = 'read';
var ajax_url = 'engine.php';
alert('link pressed for id: '+c_id);
$.get({
url: ajax_url,
data: { 'task':task, 'c_id':c_id },
success: function(res){ $('#form_map').val(res); }
});
});
});
</script>
Disregarding all that wonky Ajax calls (which also do not seem to work correctly), when I click a link nothing happens. It doesn't even run the script. I tested this by setting a breakpoint and adding the alert. Nothing seems to even trigger this.
Any suggestions on what I am doing wrong?
use:
<script type="text/javascript">
instead of:
<script type="text/css">
also use:
$('#form_map').html(res);
instead of
$('#form_map').val(res);
You may want to fix the opening tag
<script type="text/css">
to
<script type="text/javascript">
You need to return false at the end of the function you pass into .click().
$('.a_link').click(function() {
// Your AJAX stuff here.
return false;
});
Returning false stops the link from continuing to work as normal.

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Categories