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);
});
});
Related
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>
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
The JavaScript below was adapted from W3Schools. Basically, I just added the URL path to my Servlet in the JS code below.
The Servlet on the server simply returns one of two strings:
(1) GET: Hello from Ajax Server! (**GET**)
(2) POST:Hello from Ajax Server! (**POST**)
The code for the doGet() and doPost() Servlet methods is to just create a PrintWriter from the Response and write a string to it.
The JavaScript below does nothing when I run it by clicking the button. I've omitted the URL to the actual server in the JS code below since that's the customer's site.
Any suggestions would be most welcome.
Thanks,
<!DOCTYPE html>
<html>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xmlhttp.responseText;
};
xhttp.open("GET", "<path_to_server>:8080/AjaxSvr/ajax", true);
xhttp.send();
}
</script>
</body>
</html>
I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.
I have a standard html page index.php and within this page I have a
<div id="alertMe">...</div>
I use a simple onclick function to do an AJAX change of this div. I wont paste the whole Ajax call.
xmlhttp.open("GET","message.php?msg=hello" , true);
message.php loads and I can display the $_GET['msg'] value in the alertMe div. However, I have a simple javascript alert which is in the file message.php
<script type="text/javascript">
alert("I am an alert box!");
</script>
I cannot get the alert to popup. Is this because I am trying to run javascript within a div load? I would have thought that was a common requirement.
Any ideas?
==== Including files =====
index.php
<html>
<script>
function loadMsg(moduleID) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("alertMe").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","message.php?msg=hello" , true);
xmlhttp.send();
}
</script>
<body>
<div id="alertMe"></div>
Load Message
</body>
</html>
message.php
<?php
echo $_GET['msg'];?>
<script type="text/javascript">
alert("I am an alert box!");
</script>
As some of the commentators have pointed out, <script>s inside an AJAX response do not get executed when the HTML is injected into the page by setting the innerHTML property of a DOM node. If you really need to execute those scripts:
function setHtml(element, html) {
element.innerHTML = html;
var scripts = element.getElementsByTagName("script"),
i = 0, script;
for (i; i < scripts.length; i++) {
script = scripts[i];
if (script.type = "text/javascript" && !script.src) {
eval(script.innerHTML);
}
}
}
Edit: I personally recommend against this. The "success" handler for your AJAX call should contain the logic you need to run post-AJAX.