why do i always get a 404 on this function? - javascript

I'm using this function to check if a webpage exists. To do this I am checking if it has a header. But I always get a 404, even with a blank url.. what am I doing wrong here?
var xmlhttp;
function checkURL(url){
xmlhttp=null; // initialize the request object
// All the browsers except for the old IE
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send(null)
}
// old IE
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp)
{
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("HEAD",url,true)
xmlhttp.send();
}
}
}
function xmlhttpChange()
{
// if loaded
if (xmlhttp.readyState==4)
{
// if head exists "OK"
if (xmlhttp.status==200)
{
alert('URL exists')
}
else
{
alert("Status is "+xmlhttp.status)
}
}
}

It works fine for any page that you are allowed to access.
Demo: http://jsfiddle.net/Guffa/dPMah/
You can only access pages in the same domain using the XMLHTTP object.

I assume the url variable will contain addresses to completely other sites, and is not just for checking internal paths in your application? You can't AJAX to another domain like that because of the Same Origin Policy.

Related

Access is denied when try to read a local xml file using ajax request on IE only

I am trying to read a local file forms.xml from an single html page (not an application ).
Javascript code :
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","forms.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
I think my code is correct because it doing good in firefox and crome but in IE its saying
SCRIPT5: Access is denied.
on line xmlhttp.open("GET","forms.xml",false);
Now i have read some post concerning this issue they all give different solution and some say its a problem in IE 9 but i am using 10.0.9200
Possible explanation and solution please.
This is an issue with cross domain requests. XMLHttprequest needs to be called on the same domain only and running via a http request. Running your page locally with no server will cause the access denied error in IE (as well as most other browsers)
If you are just testing you can try overriding a setting in IE to see if it helps.
You can enable cross-domain on IE by going into Internet Options -> Security Settings ->Custom level and enabling "Access data sources across domains".
This piece of code is working on any older browser starting from IE5
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
alert("XMLHTTP Not Supported On Your Browser");
}
}
}
}
use xmlhttp = new ActiveXObject("MSXML2.XMLHTTP")

load json file in my firefox addon

I have a Firefox addon, in one of my js files I have an object that I use in my script.
Now I need this object online as json, so I'm going to add this json file on the server. And every time I run script the first thing it will have to do is include that file.
How can I do this with javascript?
Something similar as PHP include something?
I can't use jQuery
Have a AJAX call to the url(server file that should provide the object as response) on top of your script.
See here for AJAX call, http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Should the communication happen between domains, ie, if the file that holds JSON object hosted in abc.xom and script file that makes AJAX call hosted in XYZ.com then set Access-Control headers with response that would work with CORS enabled browsers http://enable-cors.org/client.html. For Non-CORS browser we should go with JSONP object/call.
Im trying to do this:
var locations = loadLocations();
function loadLocations() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
alert("Something went wrong!");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
//console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://.../locations.json",true);
xmlhttp.send();
}
console.log(locations);
but firefox show me error debugger eval code on line xmlhttp.send();
when i do console.log(xmlhttp.responseText); inside the functions, it shows me everything, but when i return this, dont show anything

Ajax Call not updating DIV in firefox. Working fine in Chrome

I am sending chat message, and receiving them in particular div.. All read and write with ajax. Everything works fine in Chrome, but in firefox, it does not shows...
Here is my code :-
var xmlhttp = false;
function read_message() {
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'http://<?php echo $domain; ?>/m.php?id='+<?php echo $id; ?>,true);
xmlhttp.setRequestHeader("Content-type","text/html");
xmlhttp.send();
}
$(document).ready(function(){
setInterval("read_message()", 800);
});
$domain is define in Header page and it is Same domain, where file is running... i.e,
if my chat page is in localhost than $domain is also localhost..
I am aware of same origin policy of ajax, but is this problem due to using http://.
I cannot leave http:// part as i am using url-rewriting and there my url is something like http://localhost/chat/user/anonymous so, if i use only m.php?id=1 than it tries to fetch page from
http://localhost/chat/user/m.php which obviously doesnot exist... it exist in http://localhost/m.php
if above mentioned point is error, is there any way that we can solve it, or any other better help would be great.
Thanks
When you fire two requests, if the second request fires before the first request resolves, xmlhttp.responseText in your onreadystatechange listener would point to the responseText of the second (unresolved) request when the listener for the first request fires. This is because you only use a single global xmlhttp variable that is shared for all requests.
If you define var xmlhttp inside your read_message, instead of outside of it, then each new function call will have its own private xmlhttp variable:
function read_message() {
var xmlhttp;
//...
}

Why is my basic Ajax script not working?

I have been playing around with Javascript and now I came to Ajax. I am trying to write very simple script that would get the file contents - print the txt file contents in the div with id=test. This is the script :
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET" , url ,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
when I use it on this website :
<div id="test" name="test"> HELLo </div>
<button type="button" onclick="loadXMLDoc('test1.txt')">ClickMe1</button>
With this script HELLo is substituted by nothing - the script empties the container.
Maybe I am missing something trivial but do I need PHP installed ? I don't think so but... I am not sure what is happening in here. When I am debugging the xmlhttp is empty the whole time. Why ?
You'll need to check for readyState and the HTTP response status before replacing the text;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Please let me know if it works.
For browsers other than IE
IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents). IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below. Normally you check the status of the request to see if it's been fully read or not before accessing the responseText.
Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request. (The status will always be 0 for request not made via HTTP) The best I can offer is this:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
xmlhttp.open( "GET", url );
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open( "GET", url );
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
For CHROME
If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch. Otherwise, it will refuse file system ajax requests. (You will have to set this even if using a so-called "easier" library such as jQuery).
Running AJAX apps on File System In General
Not usually a good idea, a lot of caveats to this route. Typically local development is done with a web server installed to localhost on your development machine.
Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest();
You have many other options for this.
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Firstly, you have to fight with Same Origin Policy.
A simple working code for a synchronous request is following:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.status == 200 && req.readyState == 4) {
...
}
req.open('GET', url, true);
req.send(null);
Note this is working for Firefox/Opera/Chrome. If IE, use:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests.
You don't need PHP, however you'll need apache or a similar web server.
Try with jQuery. Download the last version here and write this code snippet:
function loadXMLDoc(url) {
$("#test").load(url);
}
It's much simpler and less error prone

Load specific XML content to HTML

I'm trying to load specific content from a XML to a HTML div. I'm using a function with parameters to do this.
This my call to function:
loadDoc("news.xml","destak-article","article");
this should send a request for the xml file, get the content of «article» tag and put it on the «destak-article» div.
Here's my function body:
function loadDoc(url,id,tagname){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
But this doesn't seem to work.
On Chrome js console I get this error: Cannot call method 'getElementsByTagName' of null
On Firebug I get: xmlDoc.getElementsByTagName(tagname)[0] is undefined
Any help is much appreciated.
Did you verify the server response? Use some error checking in your code. For example:
if (xmlhttp.status == 200) {
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
else {
alert('error');
}
You need to register a handler function that will be called once the request is complete. You can see an example of how to do that here.
What's happening in your case is that you're trying to get the xmlDoc immediately after sending the request and the server hasn't had time to process the request and respond yet.

Categories