change p content with text file one - javascript

I'm coding my first website, now I'm trying to change a p content with the content of some text files, which contains long descriptions of what my site is about, actually I've tried many ways, like httprequest(), FileReader() and jquery get, but actually I haven't managed it,because I was running it locally and probably because of the wrong file position, so i created a new small code in witch I tried jquery get, I ran it on "web server for chrome" but it doesn't work.
this is the code:
<!DOCTYPE html>
<html>
<body>
<div><h2 id="demo">Lets change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
function loadDoc() {
$.get("hello.txt",function(data){
getElementById('demo').innerText= data;
});
}
</script>
</body>
</html>
when I load it, the p and the button are displayed, but when I click the button nothing happens; the .html and the .txt files are in the same folder.
I'have been stuck on it for many days, please help, and don't mark it as duplicate.
any help is appreciate.

You could try this out
<script>
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
</script>
HTML:
<div><h2 id="demo">Lets schange this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<button type="button" onclick="loadDocWithHttp()">Change Content from Http request</button>
Using AJAX:
function loadDocWithHttp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "hello.txt", true);
xhttp.send();
}

Try this
function loadDoc() {
$.ajax({
url : "hello.txt",
dataType: "text",
success : function (result) {
$("#demo").html(result);
}
});
}

First of all do one change in your script as mentioned below
function loadDoc() {
$.get("hello.txt",function(data){
$('#demo').html(data);
});
}
For that button you have to bind click with delegation method on()
$(document).on('click','<your_button_selector>', function(){
alert("hello") // replace and put your code here
});
Good Luck..!!

Instead of
getElementById('demo').innerText= data;
change to below line.
document.getElementById('demo').innerText= data;

Try this :
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').text= data;
});
}
or
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
You can use jQuery Ajax function. The error attribute will be helpful to get the exception:
$.ajax({
url: "./seeds/hello.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
},
error: function (e){
//error print
}
});

1.can u browse http://url/hello.txt in your browner?
2.open the developer tools, does any errors show?
3.getElementById have to be used under document Object

Related

Vanilla Javascript version of AJAX [duplicate]

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 4 years ago.
How can I remove the need to download a full jquery library when all I want to use is AJAX. Is there a smaller file that focuses on AJAX or is there a Vanilla Javascript version of this code?
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'cookies.php',
success: function(data) {
alert(data);
}
});
});
});
</script>
You can use the fetch function.
Here is an example from the link:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
You can try with XMLHttpRequest like below.
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "cookies.php", true);
xhttp.send();
}
</script>
</body>
</html>
Demo: https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first
Reference: https://www.w3schools.com/js/js_ajax_http_send.asp
you can use build in fetch module for example
fetch('http://yourapi.com/data')
.then(response => {
console.log(response)
});

Sending a Request To a database(google sheets)

I have created a script within google sheets. It gives a result of a cell from my table in google sheets(kinda database). I want the result send to my html page, and i have tried so far with XMLHttprequest but with no success.
What have i done wrong?
Here is the Script
<script>
function load() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://script.google.com/macros/s/AKfycby5RzvUWSEOjerJpouxN72wpsgpsF8IWQo2AvjZUdRPcqskz28/exec", true);
xhttp.send();
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="load()">Request data</button>
<p id="demo"></p>
</body>
</html>
To read a spreadsheet from google:
download a script called Tabletop and add it to your HTML. (The readme is here)
In Google Docs go up to the File menu and pick Publish to the web. Then click Start publishing. A URL will appear, something like https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html, that is the URL you will use.
Then call it with this:
<script type="text/javascript">
var public_spreadshseet_url = 'https://docs.google.com/spreadsheet/pub?YOUR_URL_HERE';
// YOUR_URL_HERE sample: hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html
// You get this URL from google docs after you publish the spreadsheet
function init()
{
Tabletop.init(
{
key: public_spreadshseet_url,
callback: showInfo,
simpleSheet: true
})
}
// This function gets called to give output
function showInfo(data)
{
alert("Successfully processed!")
console.log(data); <-- Here is the spreadsheet data
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="init()">Request data</button>
<p id="demo"></p>
</body>
</html>

ajax call to mapped URL

I am trying to make an AJAX call to a localhost URL that I am hosting via java. The URL currently only holds a String.
But when I try to call it from my javascript, I don't get any return value. The code/URL doesn't even work.
Javascript code(For website):
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'localhost:8080/highscore', true);
xhr.send(null);`
JAVA class code(currently running):
#RestController
public class Server {
#RequestMapping("/highscore")
public String highScore() {
return "test";
}
}
Why you don't using jQuery instead, as below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
req_url = "http://localhost:8080/highscore";
$.ajax({
type:"post",
url:req_url,
success:function(data){
alert('hello!');
document.getElementById('newgame').innerHTML = data;
}
});
});
</script>
</head>
<body>
</body>
</html>
Replace localhost:8080/highscore by http://localhost:8080/highscore

Javascript not loading another page into DIV

I am having some troubles today. I am trying to get Javascript to load content into a <div>. Now, this is my JavaScript source code:
function loadXMLDoc(filename) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
after_load_function(xmlhttp.responseText);
}
}
xmlhttp.open("GET", filename, true);
xmlhttp.send();
}
function after_load_function(responseText) {
document.getElementById("right").innerHTML = responseText;
}
window.onload = function () {
loadXMLDoc("welcome.html");
}
And my div:
<div id="right"></div>
Does anyone know the problem?
Is there any reason you aren't using an abstraction like the JQuery load method?
$( document ).ready(function() {
$("#right").load( "welcome.html" );
})
looks pretty good to me.
Just had a similar issue, here is what I have and it seems to be working really well,
HTML:
<html>
<head>
<title> pageOne </title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<input class='loadBtn' type='submit' value='Load a Different Page!:'>
<div id="page"></div>
</body>
</html>
JS:
//click function:
$(".loadBtn").click(function(){
//div to hide/replace
$('#page')
//fadeOut div content:
.delay(200).fadeOut('slow')
//load method:
.load
//url #divToReplace
('pageTwo.php #page')
//fadeIn new div content:
.hide().delay(300).fadeIn('slow');
//prevent default browser behavior
return false;
});

Get stuck in the XMLHttpRequest

I made a simple html to play with XHR, but get no response from httpxml.responseText;
But the script does work in the safari console.
<html><head></head><body>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<script type="text/javascript">
function loadXMLDoc()
{
httpxml = new window.XMLHttpRequest;
httpxml.open('GET','resources/xml/test.xml',true);
httpxml.send();
text = httpxml.responseText;
alert(text);// there's no text in the alert window
document.getElementById("myDiv").innerHTML=text;
}
</script>
</body>
</html>
Is it just me or are you passing "true" as the third parameter of httpxml.open? That means "perform the request asynchronously". Either change this parameter to "false" or set a readystate callback function that gets invoked when the network operation has completed.
Better example code here:
http://www.w3.org/TR/XMLHttpRequest/
You should add the readyState test before.
function loadXMLDoc()
{
httpxml = new window.XMLHttpRequest();
httpxml.open('GET','yourpage.xml',true);
httpxml.send(null);
httpxml.onreadystatechange = function() {
if(httpxml.readyState == 4) {
text = httpxml.responseText;
alert(text);
document.getElementById("myDiv").innerHTML=text;
}
}
}
But for this, I will use jquery, so easier :
$('#mybutton').click(function(){
$.GET('yourpage.xml',function(data){
$('#mydiv').html(data);
});
});

Categories