Why is XMLHttpRequest not working in local hosted file? - javascript

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();

Related

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.

How do I retrive a js script built by php using ajax and have the script run?

I am using google maps API to build my own world.
The problem I am running in to is that the data number of markers/locations cause the page to become unresponsive.
So I believe; and could be wrong; that the solution is to call only the markers/location that are with in the bounds(that is to say visible on the window) and at the zoom level.
I was thinking that if i get the bounds of the window and zoom level and pass that to a php script that would build the js marker function and then call that function.
However i have tried a rudimentary scripts that looks like it returns the function but it does not activate the script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("script").innerHTML = this.responseText;
eval(this.responseText);
}
};
xhttp.open("GET", "fjack.php", true);
xhttp.send();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div onclick="loadDoc();"> click </div>
<div id="script"></div>
<div id="demo"></div>
</body>
</html>
this is the php script:
<?php
echo "<script>";
echo "function me(){
document.getElementById(\"demo\").innerHTML=\"ITS WORKING\";
}
me();";
echo "</script>";
?>
I have tried eval() but that did nothing.
You're almost there, just return .js code from the server without <script> tags and evaluate the string using eval, so you'll have to change this:
if (this.readyState == 4 && this.status == 200) {
document.getElementById("script").innerHTML = this.responseText;
eval(this.responseText);
}
with this:
if (this.readyState == 4 && this.status == 200) {
eval(this.responseText);
return;
}
and the server(php script) response looks like this:
<?php
echo "function me(){
console.log('hello world!');
}
me();";
It works but using eval() is not the best choise; I recommend to use a function object for this(new Function('dynamic content -server response here')) or even better, a js module loader, which check your module's dependencies and dinamically loads the required js files in the right order, in the header section, using <script> tags, no need for XHR requests, as it was already mentioned in a previous reply to your question. Take a look at http://requirejs.org

Why The News Is Not Being Pulled [XML JS Query]

Here's my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>News Site</title>
<script>
window.document.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
console.log(xmlDoc);
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br/>" + xmlDoc.getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
} else {
document.getElementById("demo").innerHTML = "Can't show it.";
}
}
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
I am a beginner in using Ajax and this is my first project. I checked with the format, even validated it with W3 Validator, and it doesn't seem to work.
Nothing is showing on the page. It's completely blank.
Can anyone point out my mistake please?
The document object does not have an onload property. Using that style of event handler assignment, you are looking for window.onload.

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.

AJAX Beginner with DOMException issue

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.

Categories