Adobe AIR and multiple XMLHttpRequests is being... weird - javascript

I'm making a small Adobe AIR app (my first) using HTML+Javascript. I need to run more than one asynchronous data request, but the second one didn't seem to be firing (note that the requests were not run concurrently originally). I tried stripping the program down to the bare minimum that exhibited problems, and at first only the first request fired, but then things got strange. Code and output follows:
<html>
<head>
<script type="text/javascript" src="AIRAliases.js"></script>
<script type="text/javascript">
function download(page) {
var url = "http://en.wikipedia.org/w/api.php?action=parse&format=xml&page=" + page;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url,true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4) {
air.trace("Done");
}
}
xmlhttp.send(null);
}
function appLoad() {
download("Main Page");
download("Main Page");
}
</script>
</head>
<body onLoad="appLoad()">
</body>
</html>
Expected output:
Done
Done
Actual output:
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
Done
Done
Done
Done
Done
Done
Anyone seen anything like this before?

Simple answer, you shouldn't re-use xmlhttprequest objects (even if you don't realise you are because you're a complete noob at Javascript).
This line:
xmlhttp = new XMLHttpRequest();
Should be:
var xmlhttp = new XMLHttpRequest();

Related

Javascript loaded by an Ajax call doesn't execute?

I´m trying to implement html code with Ajax-get into my temp-page.
This works as it should, only the javascript isn´t executed as I expected. If I load the code independently in the browser, then the javascript executes as expected. If it's implemented with Ajax in my temp-page it doesn´t. Why?
Here is the html and javascript code I'm loading:
<link rel="stylesheet" type="text/css" href="/x/x/x/x/stylesheet.css">
<div id='content_Box'></div>
<script type="text/javascript" src="/x/x/x/x/javascript.js" charset="utf-8"></script>
And here is the ajax code which loads it:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content_Box.innerHTML = "";
content_Box.innerHTML = this.responseText;
}
};
xhttp.open("GET", Pfad, true);
xhttp.send();
Thank you for your time!
Your problem is not with the ajax call.
The issue is that
content_Box.innerHTML = this.responseText;
doesn't cause any scripts to execute.
See Executing <script> elements inserted with .innerHTML for some code that looks at the text, finds the scripts, and executes them.
It may depend on what your js actually does.
Anyway you can call the functions once you have loaded the ajax response (in xhttp.onreadystatechange) to make sure to run them at least once also on the parts you got from the response.

Notify after Ajax call

Hope this is an nice easy one
I want to show a notify when an ajax function completes. My ajax is fine I just can't seem to get the notify to work. I have jquery and everything installed and I also have notify.js from http://notifyjs.com/.
Using the google developer tools I just get the error below all the time.
Uncaught TypeError: $.notify is not a function
Here is my ajax function. This works just fine exactly as I need just no notify is displayed :(
function MyAjaxFunction()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainpagemenu_myDiv").innerHTML = xmlhttp.responseText;
$.notify("Hello World"); // <- **** this is the thing I want to do
}
}
xmlhttp.open("POST", "/myaspfile.aspx", true);
xmlhttp.send();
}
I have linked in my files
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and
<script src="/bootstrap/js/notify.js"></script>
Link to the following script
<script src="http://notifyjs.com/dist/notify-combined.min.js"></script>
at the top of the page (before using the Ajax function)

if (xmlhttp.readyState==4 && xmlhttp.status==200) in AJAX not executing

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.

Ajax Function Only Working Part of the Time

I am using the following Ajax function format:
var xmlhttp;
function addAddress(str)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
var addAddress = "add";
xmlhttp.open("POST", "sys.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&addAddress=" + addAddress;
xmlhttp.send(queryString);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (windows.ActiveXObject)
{
return new ActiveXObject("Micorsoft.XMLHTTP");
}
return null;
}
Up until now, all of my Ajax functions, like the one above, have been running fine. However, now the function will work only sometimes. Now, sometimes I will have to click the onclick event a couple times to execute the function or the function will just hang, and then after about 4 minutes it will execute.
I tested parts of the function and found that the issue lies some where at the:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.status);
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
When the function works, I can alert(xmlhttp.status) and get 200. However, when it's not working, the alert box doesn't even trigger. In fact, nothing happens, not even an error.
Could this be a server issue? I am kind of thinking my website got hacked, but I cannot find any issues accept that the Ajax functions are not executing properly.
Lastly, I do not get this problem on my localhost, it's only happening on the live website.
Any help will be greatly appreciated.
Thanks
First just confirm that the addAddress function is actually being called when you click the button or control that should trigger it.
Just a simple alert in the first line like this would work:
function addAddress(str)
{
alert('addAddress has been called!')
....
}
If you don't get the alert, make sure there isn't a javascript error on the page that is preventing the function from running. In firefox you press CTRL+SHIFT+J to see the error console for example.
If that part is working, trying putting the URL for the ajax request directly into your browser and diagnose it that way.
Looks like you are requesting this url with ajax:
sys.php&addAddress= (address goes here)
Check that the page will load directly in your browser. If not, the problem is not the ajax request, but something with the sys.php page itself - which you can then drill down on.
Hope that helps!
This wasn't the answer I was expecting, but I ended up having my web host (GoDaddy) change servers, and that resolved the problem. For almost a year, I was running IIS7 with PHP. Since I had never run into any problems, I just continued using that server. After the Ajax latency issue and not being able to figure out a solution, I figured I would just switch over to Apache. After the change, everything started running smoothly again.
I am thinking maybe there was a software update that I was not notified about. Or, maybe my website was getting hit with a DDoS, which was decreasing the performance of my Ajax requests. Lastly, maybe someone got into IIS and changed a setting. I don't know, all I know is that the minute the server was changed over to Apache was when the website started running normally again.
Thanks for everyone's suggestions.

Adding a simple GET or POST in ajax?

I know what GET and POST methods are in ajax, but i was wondering how to implement them into a simple code so i can understand it better, and here's a simple code i found:
<html>
<head>
<title>XMLHttpRequest in Mozilla</title>
<script type="text/javascript">
function Start()
{
try
{
xmlhttp = new XMLHttpRequest();
document.getElementById("Content").innerHTML="<h1>Using XMLHttpRequest Object</h1>";
}
catch (e)
{
document.getElementById("Content").innerHTML="<h1>XMLHttp cannot be created!</h1>";
}
}
</script>
</head>
<body>
Start
<div id="Content"></div>
</body>
</html>
The only thing you're achieving there is to determine whether your browser supports XMLHttpRequest or not (no in explorer, yes on anything else). You are not actually calling the server.
This is a nice link to start learning ajax and javascript in general:
http://www.hunlock.com/blogs/AJAX_for_n00bs
Be sure you check all the site, not only that post.
function ajaxRequest() {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest) { // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null) { // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
var url='http://somedomain.com/getdata.php?doc=sometext.txt'; // This is the URL we will call.
AJAX.open("GET", url, true); // Open the url this object was set-up with.
AJAX.send(null); // Send the request.
AJAX.onreadystatechange = function() { // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete") { // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
}
// End Ajax readystate check.
} // End Event Handler.
}
A good place to get started : https://developer.mozilla.org/en/AJAX/
Your snippet of code will only work in non IE browsers. Don't leave MS out of the party! Use this code
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
Now you can use this object to carry out a request or two.
There's a very comprehensive tutorial here : https://developer.mozilla.org/en/AJAX/Getting_Started
That tutorial will explain it much better than I ever can.
I would like to suggest something that will make your life a whole lot easier. Use jQuery! It makes ajax calls (and anything javascript) much easier. You can do complex operations with very little code.
http://api.jquery.com/jQuery.ajax/
This is for your refrence.
If you are really into Javascript and want to learn AJAX in simple way, I would suggest you the http://w3schools.com/ajax/ajax_intro.asp which is pretty basic and easy to understand. You can even try out there what you have learnt so far.
Also, Jquery is pretty simple as far as Ajax is considered. It basically frees you from all the mess of checking for the browser compatibilities and other stuff. I suggest you take a look at what Elad has mentioned in the above. "Write Less Do more" is the tag for Jquery. Just give it a try.

Categories