I have the following code that works fine in IE:
<HTML>
<BODY>
<script language="JavaScript">
text="";
req = new XMLHttpRequest();
if (req)
{
req.onreadystatechange = processStateChange;
req.open("GET", "http://www.boltbait.com", true);
req.send();
}
function processStateChange()
{
// is the data ready for use?
if (req.readyState == 4) {
// process my data
alert(req.status);
alert(req.responseText);
}
}
</script>
</BODY>
</HTML>
In IE, the first alert returns 200, the second returns the web page.
However, in Chrome the first alert returns 0 and the second returns the empty string.
My intent is to grab a web page into a string for processing. If I'm not doing this right, how should I be doing this?
Thanks.
In general, due to the same origin policy (for security reasons), you can't make request to URLs outside your domain. So, if your domain isn't boltbait.com, you can't make that request. What's strange is that IE doesn't give you an error...
However, in Chrome, an extension can make cross-origin requests (check this).
Related
I am working on javascript where i am trying to access a url path using xmlhttprequest . the code works fine with activexobject ( i dont want to use activex object ) . when i try to call it using xmlhttprequest it does not work . it gives an error saying access denied. i am using IE8 version here . I have already tried the below workaround
enabling the "access data sources across domain in internet option"
adding trusted sites
if(src) //scr = templates/mytemplate
{
try{
var xhr= new XMLHttpRequest(); //new ActiveXObject("Microsoft.XMLHTTP"); works fine
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
log.profile(src);
if(xhr.status==200||xhr.status==0)
{
//do some action
}
}
element.html(xhr.responseText);
log.profile(src);
xhr.open("GET",src,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(null);
}}catch(e){
alert("unable to load templates"+e); // here i am getting error saying acess denaied
}
Here, you got Access denied error. Looks like you are directly trying to run the HTML page in IE browser. You need to host the web page on any web server. for testing purpose, I hosted this sample page on IIS server. Than you can try to access the web page from IE will help to visit the page without this error.
I tried to make a test with this sample code and I tested it with IE 11 (IE-8 document mode).
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Output:
Based on my testing result, code is working fine with the IE-8 document mode so it should also work in IE-8 browser.
I am really new on javascript. I want to read xml from an url and want to parse it on html. I have html and javascript codes like that:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
What is wrong ? thanks
This is the standard method to do this task:
Since people keep going along the path of trying to use cross domain for something other than JSONP... IT WILL NOT WORK!
The following code below is an example of what will work, as your server is allowed to get content from other network locations being its more controlled.. Your browser on the other hand can only receive JSONP or PLAIN TEXT... Most google results should explain this as well..
YOUR ONLY OPTION
Is to use a PROXY of some form to obtain what your trying to access, So you only have three choices here.
Use JSONP or Plain Text
Use a Proxy or some other method that is local to your server/website/script/page
Keep trying to use examples posted here after being told cross domain rules apply.
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP: myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
Please note that is you plan to use this with other types of content then you will need to change/remove the header line.
YOUR BROWSER ALLOWS YOU TO AJAX XML FROM OTHER WEBSITES
If this is the case, then you need to replace or update your web browser..
THE ABOVE SOLUTION IS NOT COMPLEX
This is virtually copy and paste code ready to go, The JS function will return the result/data/content in the three most know ways...
The PHP script is a copy and paste as well.. So if you have PHP installed.
All you would need to do is create a new text file in the same location as your html document and name it as "myproxy.php" and this example will work.
This is a proper XmlHttpRequest with a callback function to handle your XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
This is working code so you can just erase what you have and put this directly in place of it. Good luck!
If you're planning on hosting the file on your own server to access via XHR, the code I offered is intended for that. If w3schools.com had a 'Access-Control-Allow-Origin: *' header on the XML file your are requesting, it would also work. But they don't. So you need to have the XML file in a place where your browser's security will let you access it (same domain origin as your webpage). Otherwise your browser will continue to block the resource with a 'cross-origin-request-blocked' error in the console.
I was trying ajax on my page. But it is not working as if (xmlhttp.readyState==4 && xmlhttp.status==200) is always false. I have alerted the values of xmlhttp.readyState and xmlhttp.status. There values are always 1 and 0 respectively for xmlhttp.open event and 4 & 0 respectively for xmlhttp.close event.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function captcha_check()
{
var code = document.getElementById("captcha").value;
var url = "http://www.opencaptcha.com/validate.php?img='.$captcha_name.'.jpgx&ans="+code;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
alert(xmlhttp.readyState + " " + xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("captcha_error").innerHTML=xmlhttp.responseText;
return false;
}
}
xmlhttp.open("GET","captcha_check.php?img=abc.jpg&ans="+code,true);
xmlhttp.send();
}
</script>
What the issue may be and how can I solve it and make the AJAX functioning. Thanks in advance.
The correct order of calls is:
new XMLHttpRequest
xhr.open()
xhr.onreadystatechange = ...
xhr.send()
In some browsers, calling .open clears any event handlers on it. This allows for clean re-use of the same XHR object, which is supposedly more memory-efficient (but that really doesn't matter if you code properly to let the GC do its job)
So, simply put the .open call before the onreadystatechange assignment and you should be good to go.
Even though your code is working perfectly, as mentioned in the comments, since your already included jQuery try:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function captcha_check() {
var code = document.getElementById("captcha").value;
var url = "http://www.opencaptcha.com/validate.php?img='.$captcha_name.'.jpgx&ans="+code;
jQuery.get("captcha_check.php?img=abc.jpg&ans="+code", function(data) {
alert("Load was performed.");
console.log(data);
});
}
</script>
It almost sounds like you are making an AJAX request from a page loaded in the browser directly from the file system, rather than from a Web Server. Since you are issuing a GET request, browser caching might be an issue as well. Try appending a timestamp to the URL each time so the URL is unique:
xmlhttp.open("GET", "captcha_check.php?img=abc.jpg&ans=" + code
+ "&__cachebuster__=" + new Date().getTime());
Secondly, you need to escape the code variable to make it safe for a query string:
xmlhttp.open("GET", "captcha_check.php?img=abc.jpg&ans=" + escape(code)
+ "&__cachebuster__=" + new Date().getTime());
Lastly, please check for any occurences of $_POST in your captcha_check.php file, as this would indicate you should be issuing a POST request, not a GET request.
If:
You are loading a page in the browser directly from the file system, AJAX requests will fail
You enter non query string safe characters for the code, then you end up with an invalid URL, and AJAX requests will fail
The captcha_check.php file requires a POST request and you issue a GET request, the AJAX request will fail.
xmlhttp.open("GET","captcha_check.php?img=abc.jpg&ans="+code,true);
Please check file path, maybe its wrong path.
My goal is to create an personal application out of my ActionScript3 video player. I want to be able to hold keep the single .swf file in my browser and through AJAX, pass the .swf the url to my videos. I've chosen to use JSON as my data.
I'm new to JSON and I've hit a wall. It seems completely easy, but at first I wasn't even able to even get my locally hosted .json file into my webapp. It was working when I tried to do this with XML. After a bunch of trouble shooting, it is now in fact getting my XMLHttpRequest.
I'm trying to keep with backwards compatibility as much as possible, and thus I'm using the json2.js library to secure that notion.
My current issue is not being able to parse my XMLHTTPRequest. To be honest, I'm not even sure if what I'm doing is right as everywhere I look for examples, they're almost all pointing to a solution that writes the JSON into the actual webpage.
My external JSON file: test.json.
{ "video":"test.f4v", "thumb":"test.jpg", "title":"The test", "caption":"TEST TEST TEST TEST TEST", "minutes":01, "seconds":43 }
I'm positive the JSON file is valid.
Here is my html/javascript:
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
window.onload = initAll();
function initAll(){
var jsonData = {};
var xhr = false;
if(window.XMLHttpRequest){ //Chrome, Firefox, Opera, Safari, IE7+
xhr = new XMLHttpRequest();
} else if(window.ActiveXObject){ //IE5 + IE6
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Could not make XMLHttpRequest");
}
}
}
if(xhr){
xhr.open("GET", "js/ajax/test.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200){
try{
jsonData = JSON.parse(xhr.responseText);
alert(jsonData.title);
document.getElementById("vidtitle").innerHTML = xhr.responseText.title;
document.getElementById("vidcaption").innerHTML = jsonData.caption;
} catch(e){
alert("Unable to parse jsonData.");
}
}
};
xhr.send(null);
}
}
</script>
</head>
<body><div class="vidcontent">
<h2 id="vidtitle"></h2>
<p id="vidcaption"></p>
I'm doing this locally on my server, but I have uploaded the files to my web host and still get the same issues.
Firebug tells me it has the data and I can even read it through the console. Now, The code works in Firefox, but not Chrome or IE8 (IE8 Works occasionally when I put it into compatibility mode, but not always <.< ) I can't test on Safari or Opera right now.
Is there any way I can get this working in these browsers? I have attempted $.parseJSON in the JQuery library, but I was having issues with that as well. I am interested in JQuery as well if anyone can explain the solution with it.
Your JSON is invalid: http://www.jsonlint.com/
Leading 0's are not allowed in numbers apparently.
I've been experimenting with Ajast and it's very useful for getting remote URL sources etc. In the below example it bypasses same-domain-policy and gets "Hello World !", but I cannot recreate this when I change it to google.com.
<html>
<head>
<script type="text/javascript" src="http://ajast.org/ajast/ajast.js"></script>
<script id="TestScript" Language="javascript">
function test()
{
var xmlhttp = new AJAST.JsHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4) // 4 = "loaded"
{
if (xmlhttp.status == 200)
document.write(xmlhttp.responseText);
else
alert('ERROR: ' + xmlhttp.status + ' -> ' + xmlhttp.statusText);
}
}
xmlhttp.open("GET", 'http://riffelspot.com/ajast/ajast_full.php', false);
xmlhttp.send();
}
</script>
</head>
<body onload="test();">Please wait...</body>
</html>
</code>
My problem occurs when I change the get url to google.com, can anyone help me? I want JavaScript to fetch the source of a page.
Read the documentation.
AJAST can only be used to send a request to a compatible server-side script.
Basically, it's a non-standard form of JSONP.
I thought that dynamicly loading the script into the DOM would bypass this security feature, like the quote suggests
"The main advantage of AJAST is its ability to make requests to foreign hosts (cross domain) which a standard AJAX request cannot do using a technique known as 'the script tag hack'. "
Where would I be able to find documentation as i dont want to use a JSONP proxy, I would like to request the webpage without signing.