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

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.

Related

POST data with ajax

I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help

How to manually enter POST data into browser

I'm debugging my php script and need to try to post data to by manually inputting it into the URL in my browser.
The javascript which sends the request is below. How do I enter the correct data into my browser so it's encoded in the same way as the javascript function? I tried encoding the string with http://meyerweb.com/eric/tools/dencoder/ and putting sendmail.php?q="the encoded string"... but that didn't work. Do I have to add more information?
function SendPHP(str, callback){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
xmlhttp.open("POST","sendmail.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
inProgress=false;
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (inProgress==false){
inProgress=true;
xmlhttp.send(str);
}
else{
writeDisplayConsole("ERROR: xmlhttp fired twice!");
}
}
Use the Chrome Rest plugin extension https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
You may want to look at Fiddler - the web debugging proxy. https://stackoverflow.com/questions/tagged/fiddler
One of Fiddler's features is Composer, which lets you edit a previously seen request, or create a new one from scratch. Check out e.g. this answer, it deals with a very similar issue: check POST request with Fiddler

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.

XMLHttpRequest (Ajax) Error

I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is.
I have to parse an XML file and assign its contents to the webpage - here's my code:
<script = "text/javascript">
window.onload = onPageLoad();
var questionNum = 0;
function onPageLoad(questionNum) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","quiz.xml");
try {
xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown
} catch(err) {
document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
}
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it does not run this far.
}
</script>
My XML file is inside the same directory.
<question>
<query>what is 2+2?</query>
<option>4</option>
<option>5</option>
<option>3</option>
<answer>4</answer>
</question>
Just for reference, I typically program in C# or Java, and I'm running my website on Google Chrome.
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
I see 2 possible problems:
Problem 1
the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it
Solution:
assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
Problem 2
the XMLHTTPRequest object does not exist in all browsers (by that name)
Solution:
Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}

Javascript not executed in Ajax responseText

The following is not my actual project, but an example that has the same problem as my project.
Here's the main HTML page snippet:
<div id="divExample">Before</div>
<script type="text/javascript">
loadExample();
</script>
Here's the javascript file snippet:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('divExample').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mypanel.html",true);
xmlhttp.setRequestHeader("If-Modified-Since", "Sun, 31 Dec 1899 23:59:59 GMT");
xmlhttp.send();
Here's the fetched mypanel.html:
After
<script type="text/javascript">
alert("Fetched script is working.");
</script>
When I load the main HTML page, the AJAX javascript runs fine. It fetches mypanel.html and puts its contents in divExample.innerHTML. The word "After" correctly shows instead of "Before".
However, the script with the alert never executes. I would not like to separate the alert script from mypanel.html. Any ideas how I can make it execute after AJAX loads it?
I've read here that this can be done.
I've read here that this cannot be done.
Any ideas how to make it happen?
You would want to take care to prevent arbitrary code from being run, but something along these lines could work:
...
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var myDiv = document.getElementById('divExample');
myDiv.innerHTML = xmlhttp.responseText;
var myScripts = myDiv.getElementsByTagName("script");
if (myScripts.length > 0) {
eval(myScripts[0].innerHTML);
}
}
...
In case for people, who still can't figure out,
1- check if your xmlhttp contains response key.
2- If present, then use xmlhttp.response instead of xmlhttp.responseText;
** if php is your backend server, do print_r(javascrip_code_as_string); then return;

Categories