basic xmlHttp question - javascript

I 'm having some trouble with my javascript code calling my php. Does anyone see an error in the following code? I swear I'm using code just like this on another part of the site...
var xmlHttp = createXmlHttpRequestObject();
var favSongArray = [];
function createXmlHttpRequestObject(){
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch(e){}
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp){
alert("sever is available");
//if yes try
try{
xmlHttp.open("GET", "php/getUntimed.php", true);
xmlHttp.onreadystatechange = function(){handleRequestStateChange();};
alert("attempted to call p_handleRequestStateChange_test");
xmlHttp.send(null);
}//end try
catch(e){
alert("Can't connect to server: \n" + e.toString());
}//end catch
}//end if xmlHHttp
}//end function
function handleRequestStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
u_handleServerResponse();
}//end try
catch(e){
alert("Error reading the response: " +e.toString());
}//end catch
}//end if
else{
alert("There was a problem retriving the data:\n" + xmlHttp.statusText);
}//end else
}//end if
}//end function
function u_handleServerResponse(){
//need to clear array each time
var response = xmlHttp.responseText;
favSongArray = response.split("+");
alert("made it here");
//getFlashMovie("trackTimer").trackTimer(favSongArray[0]);
}
process() is called from an onSubmit trigger. I keep getting a xmlHttp.status of zero. Does that make sense to anyone? Thanks

status == 0 usually means it was aborted -- either by pressing ESC or by changing the current address.
Or, since you're using a global xmlHttp, you may be calling open and/or send before the last request has had time to finish. Not entirely sure which, but one of them starts by calling abort.

Just navigate here.
http://docs.jquery.com/Ajax
Simple Example:
$.get('MyUrl.aspx', 'MyId=' + id, function(data){
$(data).appendTo($('#MyDiv'));
});

As Jonathan Lonowski says, status == 0 means aborted, and you said you execute that script onsubmit which would trigger the form to submit, thus reload the page and aborting the Ajax request. Take a look here too.

Why don't you try using ajax frameworks? Like jQuery for example.

Related

Can you catch a connection error?

I tried a lot of things to catch the error of this code but somehow I couldn't catch its error.
I have tried the try and catch(err) method but the error just pops up. Can't find an article on how to catch server connection errors either. They pop up in my console log but I can't seem to catch them. Here is what I've tried so far... well one of the ways I tried.
function timrec(){
try{
var time;
var inter1sec = setInterval(frame, 1000);
function frame() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
time = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = "Date is: "+time.d+"-"+time.m+"-"+time.y+" <br> Time is: " +time.h+":"+time.mi+":"+time.s+ " <br> day of the week is: "+ time.dow + "<br>";
}; }
xmlhttp.open("GET", "date.php",true);
xmlhttp.send();
}
}
catch(err){
alert("Warning! Connection error! Server might be down!");
}
}
I use the code to get the time of the server by intervals but can't seem to catch its error when I try and refresh my WAMP server to simulate a server connection failure.
Is it even possible to catch that?
If it's possible can ya share? And if it's not... thennnnn this'll be a fail. Either that, or my professor just threw me a trick question or something. Not gonna be the first time tho. :/
Use this code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://www.google.com", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) { // request completed. we have some results
if (xmlhttp.status === 200) {
console.log(xmlhttp.responseText)
} else {
console.log("Oops", xmlhttp.statusText);
}
}
};
xmlhttp.send(null);

There is a delay before html textbox value gets updated after ajax function execution

I am using jcaptcha for image verification in my form. Before the form is submitted I make an ajax call using javascript to validate the text entered by the user corresponding to the image displayed. I get the result and update the value of a textbox(imageVerification). After the function that makes this ajax call is executed I pick up the value from this just updated textbox(imageVerification) for the result.
Here is the problem: I am not able to pick up the value from this textbox(imageVerification).
it always shows up as blank.
Catch: if I use an alert() before picking up the value, I am able to pick up the value correctly. I ran this in firebug debug mode and found out that it works in debug mode even without using the alert.
It seemed there is a delay before which the value in the textbox(imageVerification) gets updated. So i introduced a setTimeout() method and was able to pick up the value.
But I dont feel this is the right solution. I am assuming javascript executes sequentially. So why is my statement which is picking up the value after it has been updated by a method not able to get it immediately. Result is even though the image verification is successfull, my check fails since it is not able to pick up the result value from the textbox.
Also, if I use a simple function to update the textbox(imageVerification) instead of a ajax call, I dont face this problem.
Here is the code I am using for the ajax call.
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid);
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(parameterString);
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1)){
//document.getElementById(containerid).innerHTML = req.responseText
//document.getElementById(containerid).value=req.responseText;
document.forms['ratingForm'].elements[containerid].value = req.responseText;
}
}
This is the function for image verification:
function validateImage(){
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
fetchContainerContent('captchaController','imageVerification');
var obj = document.forms['ratingForm'].elements['imageVerification'];
//alert('val '+obj.value);
var vall = obj.value;
if(vall=='PASS'){
return true;
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
return false;
}
}
post my call to fetchContainerContent('captchaController','imageVerification'), the value for imageVerification textbox should be set. If I use the alert box which is commented after the fetchContainerContent('captchaController','imageVerification') call it works fine.
Please help me out. Thanks alot
UPDATED ANSWER: Misread program flow on first pass.
The basic problem is you're trying to get an immediate response from the validateImage() function (return true or false) when the XMLHttpRequest needs time to complete.
Move the actions taken based on the return to their own functions (validFunction, invalidFunction) and try this:
function validateImage() {}
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
var obj = document.forms['ratingForm'].elements['imageVerification'];
validReq = fetchContainerContent('captchaController','imageVerification');
validReq.onload = function () {
var validResp = this.reponseText;
if(validResp=='PASS'){
validFunction();
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
invalidFunction();
}
}
validReq.send(parameterString);
}
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return req;
}

In a .js file can I update a variable after ajax responsetext is processed?

So I have a .js file that I need to retreive a variable from a PHP file. No, I can't make the server treat .js as a .php though.
So anyway, I have this script
function getPHPVariable(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
variableIWant = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "phpfile.php", true);
ajaxRequest.send(null);
}
Now the variableIWant is what I need to be used in another string later on, but everytime I call it it is shown as undefined. I do know that the variable is being sent properly though because by simply adding alert(variableIWant); underneath the responseText line, it properly alerts me of the variable.
So for simplicity, is it possible to get the variableIWant and use it in another string, or am I SOL because it has to wait for the readystate?
Where do you define variableIWant?
If you just assign it inside the onreadystatechange function it's just available within the scope of that function.
So you have to either declare it outside all of the functions or write
window.variableIWant = ajaxRequest.responseText;
UPDATE: just as Quentin points out, just put the code inside the onreadystatechange function...
either:
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
variableIWant = ajaxRequest.responseText;
longString = "The variable I retrieved is: "+variableIWant+". Isn't this nice?";
document.getElementById('theDivPart').innerHTML = longString;
}
}
or:
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
update(ajaxRequest.responseText);
}
}
function update(value) {
longString = "The variable I retrieved is: " + value + ". Isn't this nice?";
document.getElementById('theDivPart').innerHTML = longString;
}
http://jsfiddle.net/roberkules/JgZ2B/
by the way, is there a reason why you don't use a javascript framework? e.g. like jquery that takes care of all the ajax hassle? your code in jquery:
<script type="text/javascript">
$.get('http://sumary.org/phpfile.php').done(function(data){
$(function() {
$('#theDivPart').html('The variable I retrieved is: ' + data + '. Isn\'t this nice?');
});
});
</script>
<body>
<div id="theDivPart"></div>
</body>
So for simplicity, is it possible to get the variableIWant and use it in another string, or am I out of luck because it has to wait for the readystate?
It has to wait for the readystate function to be called, and that won't happen until the HTTP response returns.
Put your logic in the function you assign to readystate, that is what readystate is for.

INVALID_STATE_ERR: DOM Exception 11

Ok, I've created a working javascript ajax file, but it generates an absurd number of these dom exceptions. I'm not sure why that is, because from what I can see, all the elements I call are currently still in existance.
The code is here:
window.onload = function(){init();}
function init() {
ajax = ajaxInit();
setInterval(function(){ajaxContact(ajax);},2000);
ajaxContact(ajax);
ajax.onreadystatechange = function() {update(ajax);}
}
function ajaxInit() {
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (ajax) {
document.getElementById("status").innerHTML = "AJAX initialized";
return ajax;
}
else {
docuement.getElementById("status").innerHTML = "Error: AJAX not available";
return false;
}
}
function ajaxContact(ajax) {
try {
ajax.open("GET","updateAjax.php?" + "ran=" + Math.random(),true);
ajax.send();
}
catch (err) {
alert(err.message);
document.getElementById("status").innerHTML = "Error contacting server";
document.getElementById("loading").src = "images/redx.png";
}
}
function update(ajax) {
if (ajax.readyState==4 && ajax.status==200){
dataObj = eval('(' + ajax.responseText + ')');
document.getElementById("status").innerHTML = dataObj.status;
document.getElementById("frameNumber").innerHTML =
"Frame:" + dataObj.firstFrame + "/" + dataObj.lastFrame;
document.getElementById("thumbnail").src = dataObj.imgSrc;
}
if (ajax.status==404) {
document.getElementById("status").innerHTML = "Ajax updater not found";
document.getElementById("loading").src = "images/redx.png";
}
}
You are probably trying to call open and send on ajax, but it throws errors if the request has not finished within the two seconds between each call by setInterval. You need to check in each call whether the ajax object has been sent already or is ready for opening (check ajax.readyState).
In Chrome, the line
if (ajax.status==404) {
causes the error by accessing the status before ajax.readyState is HEADERS_RECEIVED (2), LOADING (3), DONE (4). Try making it
if (ajax.readyState == 4 && ajax.status==404) {
to make sure that the object is ready before accessing the status.

Sending an AJAX Request - Can't get to work

I'm trying to make an AJAX GET request, but I simply cannot get it to work. I want to retrieve the HTML source of example.com. I've previously used JQuery to send AJAX requests, but I use JQuery only for its AJAX capabilities so it's a waste to include the 30KB file for one task. What is it that I'm doing wrong?
<script type="text/javascript">
var XMLHttpArray = [
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject(){
var xmlhttp = false;
for(var i=0; i<XMLHttpArray.length; i++){
try{
xmlhttp = XMLHttpArray[i]();
}catch(e){
continue;
}
break;
}
return xmlhttp;
}
function AjaxRequest(url,method){
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) return;
return req.responseText;
}
req.open(method,url,true);
req.send(null);
}
function MakeRequst(){
var result=AjaxRequest("http://example.com","get");
alert(result);
}
</script>
Returning a value from your state change handler won't do you any good - that code is waiting for something to happen, and it's invoked from the browser innards as the HTTP request is processed. It's asynchronous.
Instead of expecting a result like that, your state change handler must itself handle the response, as appropriate to your application.
function AjaxRequest(url,method){
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) return;
alert(req.responseText);
}
req.open(method,url,true);
req.send(null);
}

Categories