Ajax callback function behaving randomly. What have i done wrong? - javascript

I have following ajax function that behaves randomly. Sometimes alert success finally is displayed. On other occasions, second alert that is
Failure: my status is 500 is displayed.
promptId is passed on from the calling function. I have checked the prompturl and promptId. A valid value
of promptId is displayed on both occasions (success and failure). Also the audio file that I am trying to play is played in both cases (success and failure).
I can not figure out the cause for this random behavior of alerts being displayed.
If 500 error is coming then it means , resource is not found, but my app is able to access the resource(that is playing the audio file).
function ajax_playPrompt(promptId) {
alert(promptId)
var playPromptUrl = soapUrl + "?action=playPrompt&promptId=" + escape(promptId) + "&parentSessionId=" + parentSessionId;
alert(playPromptUrl);
playPrompt_http_request = getNewHttpRequest('text/plain');
playPrompt_http_request.onreadystatechange = callback_ajax_playPrompt;
playPrompt_http_request.open("GET", playPromptUrl, true);
playPrompt_http_request.send(null);
}
function callback_ajax_playPrompt() {
if (playPrompt_http_request.readyState != 4) {
alert("Returning bcause not 4");
return;
}
if (playPrompt_http_request.status == 200) {
alert("Success finally");
}
else {
alert("Failure:My status is "+playPrompt_http_request.status ); // this gives status as 500
}
}
Also to support different browser I am using:
// to provide support for different browsers.
function getNewHttpRequest(contentType) {
var myRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
if (myRequest.overrideMimeType) {
myRequest.overrideMimeType(contentType);
}
return myRequest;
}
Additional Info: I have multiple audio files. When I play an audio file the first time, I get the failure alert first time(even though audio is played), but during if I play it again, second time, success alert is displayed.

Can you try this?
function ajax_playPrompt(promptId) {
alert(promptId)
var playPromptUrl = soapUrl + "?action=playPrompt&promptId=" +
escape(promptId) + "&parentSessionId=" + parentSessionId;
alert(playPromptUrl);
var playPrompt_http_request = getNewHttpRequest('text/plain');
playPrompt_http_request.onreadystatechange = function {
if (playPrompt_http_request.readyState != 4) {
alert("Returning bcause not 4");
return;
}
if (playPrompt_http_request.status == 200) {
alert("Success finally");
} else {
alert("Failure:My status is "+playPrompt_http_request.status );
}
};
playPrompt_http_request.open("GET", playPromptUrl, true);
playPrompt_http_request.send(null);
}

Related

Ajax call is cancelled

This issue is literally driving me mad and I've already spent hours researching possible solutions :)
My problem is: I've got a script that, upon loading, makes some AJAX calls to the server. This script is a widget and is already configured for cross-domain , etc.
Everything was working fine until now when 1 request has stopped working. The crazy thing is that is only that one, the others work just fine.
You can see in the screenshot below:
This is the code I use to send AJAX requests:
ajax: {
xhr: null,
request: function (url, method, data, success, failure){
if (!this.xhr){
this.xhr = window.ActiveX ? new ActiveXObject("Microsoft.XMLHTTP"): new XMLHttpRequest();
}
var self = this.xhr;
self.onreadystatechange = function () {
if (self.readyState === 4 && self.status === 200){
success(JSON.parse(self.responseText));
} else if (self.readyState === 4) { // something went wrong but complete
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
}
};
self.onerror = function() {
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
};
this.xhr.open(method,url,true);
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(JSON.stringify(data));
}
}
And this is the call that causes the problem:
this.ajax.request(
this.getWidgetUrl() +"/check_referral_code",
"POST",
{uuid: SL.uuid, ref_code: ref},
function(data) {
if (data.response == "ok") {
// Do something
} else {
console.error(data.message);
}
},
function(data) {
console.error(data.message);
}
);
Can anybody help here?
UPDATE:
The problem seems to be intermittent. If I reload the page it will literally happen 50% of the times

JavaScript - Why the strange order of executing codes and then got stuck - XMLHttpRequest - Read URL w/ Login

My code is listed below. I added several console.log to let me locate my problem. But the return of the code is quite strange, and I didn't manage to find answers here, so I asked a new question.
var quote_data = new XMLHttpRequest();
var url = "http://SOME.WEBSITE.com/API_QUERIES?&FIELDS=VALUES&output=text"
console.log("HERE0: Begin");
quote_data.open("GET", url, true);
console.log("HERE1: After open");
quote_data.setRequestHeader('Authorization', 'Basic '+btoa('USERNAME'+':'+'PASSWORD'));
console.log("HERE2: After setRequestHeader");
quote_data.send();
console.log("HERE3: After send");
quote_data.onreadystatechange = function (){
if (quote_data.readyState == 4 && quote_data.status == 200) {
console.log(quote_data.status);
console.log('HERE4A: Works Fine');
var alltext = quote_data.responseText;
var lines = alltext.split("\n");
alert(lines);
}
else {
console.log("HERE4B: Error Reason: "+quote_data.status+" "+quote_data.readyState);
}
}
console.log("HERE5: After statechange");
var split_lines = alltext.split(",");
console.log("HERE6: End");
The return of this code is:
Return from Google Chrome
My problem is:
(1) Why after executing the part with console.log('HERE4A: Works Fine'); the code no longer move on to console.log("HERE5")?
(2) Why executing console.log("HERE5") first after console.log("HERE3") instead of executing console.log("HERE4")?
Thank you all for your attention and help!!!
Ajax call is asynchronous so HERE5 will be displayed right after this ajax call. You should move the rest of the code into the function like:
quote_data.onreadystatechange = function (){
if (quote_data.readyState == 4 && quote_data.status == 200) {
console.log(quote_data.status);
console.log('HERE4A: Works Fine');
var alltext = quote_data.responseText;
var lines = alltext.split("\n");
alert(lines);
console.log("HERE5: After statechange");
var split_lines = alltext.split(",");
console.log("HERE6: End");
}
else {
console.log("HERE4B: Error Reason: "+quote_data.status+" "+quote_data.readyState);
}
}

Page doesn't respond to HREF until AJAX completes asynchronous fetch

I have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.

Ajax - browser lag when updating content

I'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).

jQuery - load data to variable, check data and update in DIV

I make very, very simple intranet chat. I load every 2 sec data from URL to DIV. But I want (and I don't know how) load data to variable, compare data from DIV and if !=, update in DIV. And scroll to down "page" in this DIV. Please, help me stackoverflowers! :)
var chatInterval;
function chatLoad(){
chatInterval = setInterval(function(){
$('#chat-conversations').load('/AJAX/Chat.app');
}, 2000);
}
Instead of just loading it directly put it on a variable first and compare it. That's why I use .get instead of .load, .load loads the content directly into the element.
var chatInterval;
var chatContent = "";
function chatLoad(){
chatInterval = setInterval(function(){
$.get('/AJAX/Chat.app',function(data){
if(data!=chatContent){
$('#chat-conversations').html(data);
chatContent = data;
}
})
}, 2000);
}
First of all you must understand that compare all data is bad idea, you just need check that user have new messages whatever.
Also you must now about long polling and short polling good explanation.
Why its bad idea to compare all data?
Because after a 5 minutes you will receive a BIG BIG bunch of data (performance).
Hor compare if you want:
var _current_data = null;
var interval = setInterval(function(){
// your logic to receive data, we receive response from server
if(!_current_data) _current_data = response;
else if(_current_data != response){
// Render logic (insert data into html tags and return html as string)
$("div").html(render(current_data));
}
}, 2000);
You can use ajax to get the latest posts without reloading the page as you said with the interval of 2 second.
function getXmlHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
// code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// code for IE5 and IE6
}
else {
alert("Browser doesn't support Ajax..!!");
}
return xmlhttp;
}
function loadData() {
xmlhttp = getXmlHttpRequest();
if (xmlhttp !== null) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState < 4) {
document.getElementById('your-div').innerHTML = "<img src = 'loader-animation.gif'/>";
}
else if (xmlhttp.readyState === 4) {
var res = xmlhttp.responseText;
if (res.trim() !== "error") {
document.getElementById('your-div').innerHTML = res;
} else {
document.getElementById('your-div').innerHTML = "<img src = 'error.png' style='vertical-align:middle;'/>";
}
}
}
xmlhttp.open("POST", "data_loading_page.php", true);
xmlhttp.send(null);
}
}
on data_loading_page.php (any media of you use php or jsp or anything) print your posts using a while. so whenever the function calls the php page then you'll get the updates;
call the script by
setInterval(function() {
loadData();
}, 2000);

Categories