AJAX Beginner with DOMException issue - javascript

I am following along with a tutorial book on AJAX and I seem to be failing on some basic concept.
Here is the HTML and Javascript I am using (this is saved as ajax.html on my godaddy hosted web server):
<html>
<head>
<title>AJAX Example</title>
<script language="javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if (XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readystate == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>This is an AJAX Example</H1>
<form>
<input type="button" value="Fetch the Message" onclick="getData('data.txt', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message is supposed to appear here...</p>
</div>
</body>
</html>
And is the contents of data.txt (saved in the same directory as ajax.html):
<p>This is some text in a file that I am using to be</p>
<p>queried with an ajax process to display dynamically.</p>
The problem is that nothing happens when I press the button on the page. I have tried to step through the Javascript using Chrome's developer tools and I see a DOMException:
.
Can someone please point out if there is an issue with this javascript, or point me in the right direction to deal with the DOMException that I am seeing?

using the answer found here I read that my readystate should really be readyState. Changing that fixed my problem.

Related

Only one chunk of imported HTML is loading when I have two of them- how do I get both to load on page start-up?

I am using W3-Schools "include-html" https://www.w3schools.com/howto/howto_html_include.asp
It states that you can use multiple snippets. My plan was to include a header and a footer for each page by using this method.
On my index.html page I have this:
<!doctype html>
<html lang="en">
<!--Include Content-->
<script src="assets\scripts\include_content.js">
</script>
</head>
<body>
<header>
<div include-html="header.html"></div>
</header>
<footer>
<div include-html="footer.html"></div>
</footer>
<!--Scripts-->
<script>
includeHTML();
</script>
</body>
</html>
The scripts are a direct copy and paste from W3 (with minor changes to attribute names):
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain attribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
};
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
I can get the footer to run if I delete the include-html="header.html" so I know the linking is there. But I can not get both footer and header to run.
Both footer and header pages are currently identical except for the message so I know where the message is coming from.
Can you see if I am missing something or why the second <div include-html="footer.html"></div> is not working?
For all the reasons I mentioned in my comments to your question, you should just abandon the W3 Schools approach.
The simplest solution is to just use HTML <iframe> elements and no JavaScript whatsoever:
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<iframe src="header.html"></iframe>
</header>
<footer>
<iframe src="footer.html"></iframe>
</footer>
</body>
</html>
But, if you do need a JavaScript solution, using AJAX (XMLHttpRequest) is correct, but with the modern syntax, rather than what W3 Schools shows:
function includeHTML(fileName, destination) {
let xhr = new XMLHttpRequest();
// Establish the callback:
xhr.onreadystatechange = function () {
// Is the response ready?
if (this.readyState == 4) {
// Was the response successful?
if (this.status == 200) {
destination.innerHTML = this.responseText;
} else {
console.log("Response was received but not successful.");
}
} else {
console.log("Response is not ready.");
}
}
// Initiate the request:
xhr.open("GET", fileName, true);
xhr.send();
}
// Call the function with the file to include and a reference to the
// element to populate with the contents
includeHTML("header.html", document.querySelector(".header"));
includeHTML("footer.html", document.querySelector(".footer"));
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<div class="header"></div>
</header>
<footer>
<div class="footer"></div>
</footer>
<!--Reference and load your scripts just before the closing
body tag so that by the time the HTML parser reaches
this point in the document, all the HTML will have been
parsed into memory. -->
<script src="assets\scripts\include_content.js"></script>
</body>
</html>

I've this error "Could not establish connection. Receiving end does not exist" when I run ajax to load another file

I started to learn Ajax and this was the basic example to run ajax so what should I do when I face these "Unchecked runtime.lastError" errors ?
I tried Chrome extension wappalyzer but same problem and I am using xampp server.
<!DOCTYPE html>
<html>
<head>
<title>Hello Ajax</title>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readystate == 4)
{
document.getElementById("ajax").innerHTML = xhr.responseText;
}
};
xhr.open('GET','content.html', true);
function sendajax() {
xhr.send();
}
</script>
</head>
<body>
<h3>Welcome to Ajax</h3>
<button onclick="sendajax();">Click Me!</button>
<div id="ajax"></div>
</body>
</html>
The same code worked in course that I'm studying and I believe the problem in my browser or server i do not know.

Function was not defined in javascript?

I have two script files - one is perl-cgi and the other is javascript. Inside the cgi script I have written the Javascript function for retrieving data from a text file (using ajax). I then pass the contents of the data into another function called main_function(). This writes into the javascript file (seq_new.js). When I load the page, the console.log reports main_function was not defined. Then I refresh the page and the result displays. I don't know why it behaves this way.
The Perl script as follows:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
use CGI;
my $a= new CGI;
my $processId = $a->param("processId");
.
.
my $file_path = "/$processId/$file_name[1]";
print <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>RepEx - Result</title>
<script type="text/javascript" src="/min.js"></script>
</head>
<body>
<script>
file_load("$file_path","$filename");
function file_load(f1,f2)
{
var fileNm = f2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var pt = xhttp.responseText;
main_function(pt,fileNm,"$file_path",$file_cnt,"$head_st");
}
};
xhttp.open("GET", f1, true);
xhttp.send();
}
</script>
<script type="text/javascript" charset="utf-8" src='/seq_new.js'> </script>
</body>
</html>
My javascript file contains this:
function main_function (a,file_seq,main_file,fle_cnt,header_set)
{
.
..
}
The problem I am encountering
Loading the page for the first time, the console.log reports that the main_function was not defined and no results are displayed. After refreshing the page (by pressing F5 or clicking the reload button), the result is displayed.

Why is XMLHttpRequest not working in local hosted file?

I'm a beginner in HTML, PHP and web programming in general.
My first project is a PHP page connected to a MySQL database. I am using this javascript code to send information to another PHP page :
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ERP</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css.css" />
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript"></script>
<script>
function DelRow(callback)
{
alert("FIRSTALERT");
var xhr = XMLHttpRequest();
alert("SecondALERT");
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
callback(xhr.responseText);
}
};
var Comp = encodeURIComponent(document.getElementById("ComboBoxCompany").value);
xhr.open("GET", "DeleteRow.php?Comp=" + Comp, true);
xhr.send(null);
}
function readData(sData)
{
alert(sData);
};
</script>
</head>
The function is called by this bad boy right here :
<input class="btn btn-primary" type="button" value="Confirmer" name="ConfirmDel" onclick="DelRow(readData)" />
If you look at my javascript code, I've put 2 alert. The first one is appearing, but the second one is not. It seems like the getXMLHttpRequest is not working.
I'm using Google Chrome. I've found some thread saying that I need to execute this command line :
C:\Users\User>C:\Program Files (x86)\Google\Chrome\Application
--allow-file
-access-from-files
But it changed nothing.
I'm in the dark and looking for some insight.
If you aren't getting the second alert, you can pretty much rule out everything that comes after the second alert because none of it is going to be executed. This makes the problem VERY easy to track down, because it must be this line:
var xhr = XMLHttpRequest();
You're simply missing the new keyword.
var xhr = new XMLHttpRequest();

How to send web browser a loading page, then some time later a results page

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.
I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.
I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.
Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub Create_HTML {
my $html = <<EOHTML;
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<script type="text/javascript" >
var xmlhttp=false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
</script>
<title>Ajax Streaming Connection Demo</title>
</head>
<body>
Some header text.
<p>
<div id="response">PLEASE BE PATIENT</div>
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
print Create_HTML();
sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";
If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:
<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />
And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.
If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'form_with_hidden_fields' ).submit();
}
</script>
<form method="POST" action="realquery" id="form_with_hidden_fields">
<input type="hidden" name="foo" value="1" />
...
</form>
Please wait while your query is processed...
If you're interested in an AJAX solution, here's an example using jQuery:
$( '#submit-button' ).click( function() {
// show a "please wait" image
$( '#status-div' ).html( '<img src="please_wait.gif" />' ); // animated gif
// get form values
var formdata = { foo: $( 'input#foo' ).val(),
...
};
// submit form via ajax:
$.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() {
$( '#status-div' ).html( '<img src="success.gif" />' );
} );
} );
And you could attach that to a form like:
<form>
<input type="text" name="foo" id="foo" />
<input type="submit" id="submit-button" />
<div id="status-div"> </div>
</form>
The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.
See Watching long processes through CGI by Randal Schwartz.
Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub html_page {
my ( $meta_string, $results_string ) = #_;
my $html = <<EOHTML;
<html>
<head>
$meta_string
<title>Two Stage Web Page Demo</title>
</head>
<body>
Some header text.
<p>
$results_string
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
if ($cgi->param('doResults') eq "true") {
sleep(5);
print html_page('', 'Here are your results!');
}
}
else {
my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Two Stage web page demo using Ajax</title>
</head>
<body>
<h1>Two Stage web page demo using Ajax</h1>
<div id="result">
Users input form goes here.
<p>
<input type="submit" value="Here is your submit button" id="load_basic" />
</div>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";
// load() function
$("#load_basic").click(function(){
$("#result").html(ajax_load).load("/cgi-bin/slow.pl");
});
</script>
</body>
</html>

Categories