XMLHttpRequest connection check - javascript

I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts.
Looks like I messed up, but I can't see where. What should I change to make it work?

If you can use xhr2, you can learn stuff from this tutorial and rewrite your code to something like this:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
If you send request to another domain, you may get error even if it exists, if the target server has Same-Domain-Policy restriction (default). If the target server is on another domain, it must send header
Access-Control-Allow-Origin: *

Related

'Cross Origin' error message resulting from local XmlHttpRequest

I am using AJAX to display upcoming events on a website. To that end, I call a JavaScript function via onload="showEvents(3);", see the function below:
function showEvents (amount) {
// are there Events?
if (document.getElementById("eventsDiv")) {
document.getElementsByClassName("info")[0].innerHTML = 'Loading events...';
// initialize XML Http Request
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("eventsDiv").innerHTML = xmlhttp.responseText;
}
}
// send request
xmlhttp.open("GET", "./events.php?number=" + encodeURIComponent(amount), true);
xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send();
}
}
The file events.php is a PHP file in the same directory, and it connects to the database to fetch the upcoming events. The HTML header of the main website includes
<base href="http://www.my-domain.com/">
The problem: I get a "Cross Orign" error message (in Firefox), preventing my parent index.html file accessing the events.php. As I understand, this error message should not appear since I am using a resource from the same directory.
Ok that's ok, you also can do like this...
if($_SERVER['HTTP_ORIGIN'] == "http://your-domain.com") {
header('Access-Control-Allow-Origin: http://your-domain.com');

How to trigger a variable/method in python from a html file with javascript

I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.
Python
#app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)
Html
<a onclick="myFunction()">Clear database</a>
Javascript
<script>
function myFunction()
</script>
I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.
Thanks
You need to make an ajax request with javascript to /log, it would look something like this:
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do Success functionality here
}
else if (xmlhttp.status == 400) {
//Handle 400 errors here
}
else {
//All other errors go here
}
}
};
xmlhttp.open("GET", "/log", true);
xmlhttp.send();
}

Ajax call not successful

I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean

same domain xmlhttprequest access denied ie8

I'm fairly new to the world of web development and am trying to read a txt file in internet explorer 8 and compare it to source code of a website to see if they are equal. This is so I can work out if the web page is functioning correctly.
I managed to get the source code with an xmlhttprequest and have tried the same to get the text file (which is in the same domain as my web page) and I am getting an access denied error.
After some research I can see that cross-domain xmlhttprequests won't work but that's not what I'm trying to do so I'm not sure how to proceed.
Having run the same code in Firefox(current version). It will read the file but not the web page!
I don't mind which of the two browsers I end up using but at the moment each does half of what I want it to.
my code is:
function source1(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "http://website",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById('textzone').value = xmlhttp.responseText
var inputString = xmlhttp.responseText;
alert(inputString);
comparison(inputString)
}
}
xmlhttp.send(null)
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp.send(null)
}
All I need to know is why either the file won't open in ie8, or why the website source code shows up blank (in the alert) in firefox. Any help would be appreciated.
It could be a browser support issue.
Try the following code to initialize your XMLHttpRequest :
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
Check your comparison function. You should you xmlhttp1 instead of xmlhttp at 2 places
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
<!--alert(xmlhttp1.responseText)-->
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp1.send(null)
}
Try to add the if(xmlhttp.status == 200) { } stuff. Remember both of these are looping through status' "AND" readystates.
Technically you could be erroring somewhere (I'd rather not speculate on) halting progress to next request or whatever without the status check.
Also you "should" try other request techniques. ie.. xmlhttp.onreadystatechange = function(){itsReady(inputString)}; // we keep this line short and simple calling to another func that contains your status and readystate checks, response stuff, and more func.
On a pretty normal run the Loop looks like:
hi rdySte:1///status 0////////
hi rdySte:2///status 200////////
hi rdySte:3///status 200////////
hi rdySte:4///status 200////////
I ran into a lot of weird issues trying the long onreadystatechange = function (){ ... All stuff..} I successfully run a crazy set of request functionalities using the short onreadystatechange technique.
I noticed at the last minute->
is there a reason why the async flags are different between your funcs? I'd set them all to true unless you have a great reason.
This will work: (to test: 2 pages t1.php contains a num or whatever and t2.txt that has a num in sam dir as the funcs are called in)
function source1(){
var avar = 1;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "t1.php",true); // shortened f-names for ease of test
xmlhttp.onreadystatechange = function(){jsg_snd(avar)};
xmlhttp.send(null)
}
function jsg_snd(avar){
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
var inputString = xmlhttp.responseText;
document.getElementById('text_zone').innerHTML = inputString;
document.getElementById('text_zone1').value = inputString;
// alert(inputString);//
comparison(inputString)
}
}
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "t2.txt", true);
xmlhttp1.onreadystatechange= function(){jsg_snd1(inputString);};
xmlhttp1.send(null)
}
function jsg_snd1(inputString){
if (xmlhttp1.readyState==4) {
if (xmlhttp1.status == 200) {
var compareString = xmlhttp1.responseText;
//alert(compareString)
if(inputString==compareString){
//alert("Strings are equal");
document.getElementById('text_zone').innerHTML += "; Ok "+inputString+"=="+compareString+"";
}
}
}
}
Now the html in your body should look like:
<tt id = 'text_go' onMouseUp="source1();" >Go!</tt>
<tt id = 'text_zone' onMouseUp="text_zone.innerHTML = '';" >Click to clear!</tt>
<input type ='text' id = 'text_zone1' onMouseUp="text_zone1.value = '';" value = 'Click to clear!' >
The extra stuf is for ___s & giggles.

Ajax Pull Content From another webpage

So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.

Categories

Resources