Why HourGlass not working with synchronous AJAX request in Google Chrome? - javascript

I am executing a function where first I am making cursor to wait state(hourglass) and then I am sending a synchrounous AJAX request .After getting the response I am making cursor to default state.
The Actual Code is this..
// tests the smtp settings
function TestSettings()
{
var buttonparams= new Object();
buttonparams.IsCommandButton = true;
buttonparams.ButtonId = "testsettings";
buttonparams.ButtonText = "Sending Test Mail...";
buttonparams.ButtonOrigText = "Test Settings";
if(buttonparams.IsCommandButton == true)
HandleButtonStatus(true, buttonparams);
var request = function()
{
var ret = SendForm(buttonparams);
alert(ret);
}
window.setTimeout(request, 0);
}
function SendForm(pButtonParams)
{
var http;
var formdata;
http = yXMLHttpRequest();
http.open("POST", "./", false);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.setRequestHeader("Req-Type", "ajax");
formdata = xEncodePair("_object", "PrefMgr")+ "&";
formdata += xEncodePair("_action", "SmtpTest")+ "&";
formdata += GetEncodedFormData();
http.send(formdata);
if(http.status == 200)
{
if(pButtonParams.IsCommandButton == true)
HandleButtonStatus(false, pButtonParams);
return (http.responseText);
}
else
{
return ("Error " + http.status + ": " + http.statusText);
}
}
function HandleButtonStatus(pIsButtonStatusChange, pButtonParams)
{
var button = yById(pButtonParams.ButtonId);
if(pIsButtonStatusChange)
{
document.body.style.cursor = "wait";
button.value = pButtonParams.ButtonText;
button.disabled = true;
}
else
{
document.body.style.cursor = "default";
button.disabled = false;
button.value = pButtonParams.ButtonOrigText;
}
}

Try to assign:
var st = document.body.style;
and then refer to st in both functions. This could be a scope issue in AJAX callback function.
EDIT: Use callback function to restore cursor shape. Don't forget to do the same in case AJAX call fails.

Related

Form not sending message

I use heroku CORS anywhere proxy to solve CORS Access-Control-Allow-Origin in my form.
Now, my form showing message not send every time i tried to send a message. How can i solve this issue?
My form: Demo
Scripts:
const blogId="xxxxxxxxxxxxx";
var contactForm = document.querySelectorAll(".contact-form-blogger");
function an(req) {
try {
return JSON.parse(req)
} catch (req) {
return false
}
}
for (i = 0; i < contactForm.length; i++) {
var a = contactForm[i];
a.addEventListener("submit", function (submitUrl) {
submitUrl.preventDefault();
var form = submitUrl.target;
var req = new FormData(form),
cH = "blogID=" + typeof blogId !== "undefined" ? blogId : "";
req.forEach(function (cL, cK) {
cH += "&" + encodeURIComponent(cK) + "=" + encodeURIComponent(cL)
});
submitUrl = "https://cors-anywhere.herokuapp.com/https://www.blogger.com/contact-form.do";
req = new XMLHttpRequest;
req.open("post", submitUrl, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(cH);
req.onreadystatechange = function () {
var cK;
if (this.readyState === 4) {
if (this.status === 200) {
if (this.response != "") {
cK = an(this.responseText.trim());
if (cK.details.emailSentStatus == "true") {
form.reset();
var formSend = form.querySelector(".send-success");
if (formSend) {
formSend.style.display = "block";
}
} else {
var notSend = form.querySelector(".send-error");
if (notSend) {
notSend.style.display = "block";
}
}
}
}
}
}
})
}
You're using the demo server as your proxy, which is rate-limited and not open. See this announcement for details. You need to deploy it yourself and change the URL prefix to point to your version. The documentation, such as it is, can be found at the bottom of the README. Advanced options are here. You're also posting to Blogger, which doesn't accept a POST at that path (returns a 405, method not allowed).

Maintain scroll position in list

I have a select list, which is populated with my logfile. Every second javascript sends GET request to the server which reads the log file and populates the list. But after every GET request, the list scrolls back to top. What I want to do is to make the requests don't affect the scroll so I can freely scroll through the list.
<select id = "list" name=servers size=38 style=width:1028px>
<script type="text/javascript">
window.onload = function () {
if (bytes === undefined) {
var bytes=0;
}
var url = "/test/log.php?q=";
function httpGet(url)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var list = "";
console.log(xhttp.responseText);
obj = JSON.parse(xhttp.responseText);
for(var key in obj) {
list += obj[key];
if (sessionStorage.logfile == null) {
sessionStorage.logfile == "Log";
}
}
bytes = parseInt(list);
document.getElementById("list").innerHTML = sessionStorage.logfile + list;
sessionStorage.logfile += list;
}
};
xhttp.onerror = function (e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 1000;
function update() {
httpGet(url + bytes);
setTimeout(update, updateInterval);
}
update();
}
</script>
Maybe you should use SSE,check this:
http://www.w3schools.com/html/html5_serversentevents.asp, but if you just need to make the code works, here is how:
<select id = "list" name=servers size=38 style=width:1028px>
<script type="text/javascript">
//here, a new global var to keep the index;
var old_index=-1;
window.onload = function () {
//every change on select list, we register in this function..
document.getElementById("list").onchange = keepValue;
if (bytes === undefined) {
var bytes=0;
}
var url = "/test/log.php?q=";
function httpGet(url)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var list = "";
console.log(xhttp.responseText);
obj = JSON.parse(xhttp.responseText);
for(var key in obj) {
list += obj[key];
if (sessionStorage.logfile == null) {
sessionStorage.logfile == "Log";
}
}
bytes = parseInt(list);
document.getElementById("list").innerHTML = sessionStorage.logfile + list;
sessionStorage.logfile += list;
//here, back it to the old selected index
//when old_index=-1, means first execution
if (old_index==-1)
{old_index = document.getElementById("list").length-1;}
document.getElementById("list").selectedIndex = old_index;
}
};
xhttp.onerror = function (e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 1000;
function update() {
httpGet(url + bytes);
//i will not change your logic here, but you can write it using setInterval instead.
setTimeout(update, updateInterval);
}
update();
}
//here, the function to register the list index
function keepValue(evt)
{
old_index = evt.target.selectedIndex;
//or document.getElementById('list').selectedIndex;
}
</script>
EDIT:
ResponseText is in JSON format.
{"key":"2186 <option> 18:42:19.716 7963 [DEBUG main() cnet.cpp:167] Using public ip: 192.168.0.107 </option>
<option> 18:42:19.716 7963 [DEBUG main() cnet.cpp:168] Using local ip: 192.168.0.107 </option>
<option> 18:42:19.717 7963 [DEBUG init() redis.cpp:75] Initializing redis client application </option>"}

Javascript / ajax code - works in chrome and firefox but not in IE10

What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.

Unexpected } tokens in js - trying to learn ajax

I'm just trying to learn some ajax so I wrote some code for basically an address book to pull some data. My javascript is rubbish but I cannot seem to understand what I am doing wrong, the error points to function ajaxCall but I see no issue with that function either:
(function () {
var searchForm = document.getElementById("search-form"),
searchField = document.getElementById("q"),
getAllButton = document.getElementById("get-all"),
target = document.getElementById("output");
var addr = {
search: function (event) {
var output = document.getElementById("output");
//start ajax call
ajaxCall("data/contacts.json", output, function (data) {
var searchValue = searchField.value,
addrBook = data.addressBook,
count = addrBook.length,
i;
//stop default behavior
event.preventDefault();
//clear target
target.innerHTML = "";
if (count > 0 && searchValue !== "") {
for (i = 0; i < count; i++) {
var obj = addrBook[i],
isItFound = obj.name.indexOf(searchValue);
if (isItFound !== -1) {
target.innerHTML += '<p>' + obj.name + ', ' + obj.email + '<p>';
} //end if isItFound
} //end for loop
} //end if count check
}); //end ajax call
}, //end method search
getAllContacts: function () {
var output = document.getElementById("output");
ajaxCall("data/contacts.json", output, function (data) {
var addrBook = data.addressBook,
count = addrBook.length,
i;
target.innerHTML = "";
if (count > 0) {
for (i = 0; i < count; i++) {
var obj = addrBook[i];
target.innerHTML += '<p>' + obj.name + ', ' + obj.email + '<p>';
} //end for loop
} //end if
}); //end ajax call
}, //end method getAllContacts
setActiveSection: function () {
this.parentNode.setAttribute("class", "active");
}, //end method setActiveSection
removeActiveSection: function () {
this.parentNode.removeAttribute("class");
}, //end method removeActiveSection
addHoverClass: function () {
searchForm.setAttribute("class", "hovering");
}, //end method addHoverClass
removeHoverClass: function () {
searchForm.removeAttribute("class");
} //end method removeHoverClass
} //end addr object
searchField.addEventListener("keyup", addr.search, false);
searchField.addEventListener("focus", addr.addActiveSection, false);
searchField.addEventListener("blur", addr.removeActiveSection, false);
getAllButton.addEventListener("click", addr.getAllContacts, false);
searchForm.addEventListener("submit", addr.search, false);
searchForm.addEventListener("mouseover", addr.addHoverClass, false);
searchForm.addEventListener("mouseout", addr.removeHoverClass, false);
})(); //end anon function
function getHTTPObject() {
var xhr;
//in most cases this first if is executed
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
//otherwise support crappy IE6 and below
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
return xhr;
}
function ajaxCall(dataUrl, outputElement, callback) {
//get ajax object
var request = getHTTPObject();
outputElement.innerHTML = "Loading...";
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
//good ajax response..now save it
var contacts = JSON.parse(request.responseText);
if (typeof callback === "function")
callback(contacts);
} //end upper if
} //end onreadystatechange
request.open("GET", dataUrl, true);
request.send(null);
}
The javascript development tools keeps giving me an unexpected token } on line 97 but that changes all so often. Am I missing a curly brace somewhere?
I did put your code to this fiddle and fixed the errors as far as i can.
You missed some curly braces and semicolons. Also, you used ajaxCall() and getHTTPObject() before they were declared. Check it out. Unfortunately, i dont know if the problem is already fixed, but now the code is valid at least :)
Btw: (in my opinion) such long Code-Samples are always better pasted into a fiddle. Not only because you can focus on the probably messy code here while referring to the complete code sample somewhere else, also because you can make sure that there are no syntax-errors as you can quickly validate you code using jsLint before asking the question here.
You must re-check what your JSON response is, in console, and see if it is invalid.
Because at that very 97 line you say that you are parsing a response.

ajax synchronous call problem

I have an Ajax function which looks like :
function getData(p) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page =encodeURIComponent(p);
AJAX.open("GET", "page.php?page="+__page, false);
AJAX.send(null);
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
if(!__data) { return false; }
return __data;
} else {
return false;
}
}
then i have very simple loading function ( an loading image must appear in center of page ) :
function loadingImage(type)
{
document.getElementById("body").innerHTML = "<div class='loading'></div>";
}
then how i call ajax function :
var loadedData = getData("home");
if(loadedData)
{
document.getElementById("body").innerHTML = loadedData;
}
else
{
document.getElementById("body").innerHTML = "Error";
}
but the loading image won't appear, it's quite simple, but i'm stuck here , how make it to show that loading image while requesting data, then to replace loading image with loaded data. Thanks
function getData(p, cb) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page = encodeURIComponent(p);
AJAX.open("GET", "page.php?page=" + __page, true);
AJAX.onreadystatechange = function(e) {
if (AJAX.readystate === 4) {
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
cb(data);
}
};
AJAX.send(null);
} else {
cb(null);
}
}
getData("home", function(loadedData) {
if (loadedData) {
document.getElementById("body").innerHTML = loadedData;
}
else {
document.getElementById("body").innerHTML = "Error";
}
});
Use async = true in the .open call.
Bind an eventhandler to readystatechange. If the readystate is 4 (LOADED) then get the data and send it to your callback.
If the AJAX fails call the callback with null or false.
In your callback get the loadedData and either render it or throw an error if there is no data.

Categories