Some minor question(just interested), in every AJAX request docs they set it to true(async).
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//some code here
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
But the JavaScrips is asynchronous language plus onreadystatechange already means that the request is async and here is the question, should you always specify "true" and why?P.S Maybe there is something minor happening behind the scenes?
Yes, you should. Synchronous AJAX blocks the UI and is deprecated, you should not use it.
Note that the default is true, so you can just leave that argument out. You only need to provide it explicitly if you have to use additional arguments after it.
Related
I am trying to find out if we can integrate an API response within Aframe scene. For example, I want to get the information about an entity object when I move my cursor over it.
I know we can have maintained these static data with an a-text, but I am looking for AJAX based integration so that I can add/edit data from the backend.
Please advise.
You could use a custom component, which will grab the text and use it as an <a-text> value. Execute the AJAX call inside an event listener (like a click, or any other one):
AFRAME.registerComponent("foo", {
init: function() {
let self = this.el
this.el.addEventListener("click", (e)=>{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
self.children[0].setAttribute("value", this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
})
}
})
In a setup like this:
<a-entity foo>
<a-text></a-text>
</a-entity>
Something like this, exept with the ajax call, i took the ajax code from w3schools.
I have a custom webserver, and some content that has been working for probably 18 months or more. The code has not been touched in all that time. But, I now find one feature, which depends on Ajax, is no longer working. The problem is on the browser side. Sadly, the Ajax code was found using Google, and even when I customized it, I didn't really understand it, but it has worked until some time in the last 6 months or so. Now that it's no longer working, I'm kinda lost....
What the code does is pretty simple. My HTML form is a tab control. One of the tabs is used for displaying error messages. The Ajax code sends a GET request for "\ATCStatus.txt" roughly once per second. The server responds with:
HTTP/1.1
Server: arduino
Content-Type: text/plain
#ATCErrorFlag#
where #ATCErrorFlag# gets replaced with wither "true" or "false". If "false" is returned, nothing happens. If "true" is returned, then the Ajax code sends a request for "\ATCErrorPage.htm", which switches to the error tab, and displays the error message.
The server receives the requests, processes them, and sends the correct response, but Ajax code acts like no response was ever received, and I can't figure out why.
Anyone here know enough Ajax to have a clue?
Here is the Ajax code:
setInterval(PollATCError, 1000);
function PollATCError()
{
var xhr;
if (window.XMLHttpRequest)
xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
xhr = new ActiveXObject("Msxml2.XMLHTTP");
else
throw new Error("Ajax is not supported by your browser");
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
clearTimeout(xhrTimeout);
var response = xhr.responseText;
if (response == "false") {
// Do nothing
} else if (response == "true") {
// else, throw up Error Page
window.location.replace('ATCErrorPage.htm');
//document.getElementById("tab4event").click();
}
}
}
xhr.open('GET', 'ATCStatus.txt', true);
xhr.send(null);
var xhrTimeout = setTimeout("ajaxTimeout();", 900);
function ajaxTimeout()
{
xhr.abort();
// Note that at this point you could try to send a notification to the
// server that things failed, using the same xhr object.
}
}
What seems especially odd is that I don't ever seem to get any state change notifications. If I make the first line of the state change handler an alert(), the alert never comes up. The request does go to the server, the correct response is sent back to the client, but seems to never be seen by the XMLHttpRequest object. Even the 900mSec timeout never happens.
This used to work very nicely! What has gone wrong?? How can I get to the bottom of this?
Regards,
Ray L.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Can someone please help me understand the sequence of execution here?
xhttp.onreadystatechange is called with an IF waiting for the State ==4. But it's not 4 until xhttp.send() is triggered further down in the code. So once xhttp.send() triggers State=4, why is then onreadystatechange called again to execute the IF? I guess I'm looking at this as a top-down execution. I just don't get how/why onreadystatechange "waits" for State to change? Since its code has already been executed. Please explain as simply as possible and thanks.
onreadystatechange is an event handler, which means it triggers when a specific event fires.
The XMLHttpRequest.onreadystatechange property contains the event
handler to be called when the readystatechange event is fired, that is
every time the readyState property of the XMLHttpRequest changes
(emphasis mine)
When some action is invoked in my page, I make two ajax calls (A, B) to two different methods on my server.
Most of the times each request gets its matching response, but here and there both requests gets the same response! (of one of the requests - A,A or B,B)
The Ajax calls are made using JQuery and the server methods are implemented using Play! framework (in java).
Does anyone have any idea why does it happen and how to resolve it?
Thanks!
Ajax Call A:
var renderTypePreviewPageRoute = jsRoutes.com.eyeview.connectad.controllers.solutions.FeedLibrary.getFeedTypePreviewPage(feedHashId, feedType);
// Makes an ajax call that gets the rendered solution page
$.ajax({
// Sets the route (URL) of the server call
url:renderTypePreviewPageRoute.url,
// Sets the method (GET / POST) of the server call
type:renderTypePreviewPageRoute.method,
//data:{ hashId: feedHashId, feedType: feedType, withPreview: withPreview }-->
// In case of success
success:function(result) {
var typePreviewElement = $('#typePreviewSection');
// Set the feed preview section html content to the rendered content got from the server
typePreviewElement.html(result);
typePreviewElement.removeClass('hidden');
$('#feedPreviewGrid tr:eq(1)').removeClass('hidden');
if ($('#feedPreviewSection').is(':visible')){
typePreviewElement.show('blind');
}
var feedURL = urlEle.val();
if (waitForFileTypePreview && feedURL != "") {
feedEditNS.renderFilePreviewSection(true);
}
},
// In case of failure
error:function(xhr, ajaxOptions, thrownError) {
// Shows the error message
showError(xhr.responseText);
// Clears the preview section
feedEditNS.clearTypePreviewSection();
var feedURL = urlEle.val();
if (waitForFileTypePreview && feedURL != "") {
feedEditNS.renderFilePreviewSection(true);
}
}
Ajax Call B:
var renderFilePreviewPageRoute = jsRoutes.com.eyeview.connectad.controllers.solutions.FeedLibrary.getFeedFilePreviewPage(feedHashId);
// Makes an ajax call that gets the rendered solution page
$.ajax({
// Sets the route (URL) of the server call
url:renderFilePreviewPageRoute.url,
// Sets the method (GET / POST) of the server call
type:renderFilePreviewPageRoute.method,
// In case of success
success:function(result) {
// Set the feed preview section html content to the rendered content got from the server
$('#filePreviewSection').html(result);
// Shows the feed preview section
$('#verticalLine').show('blind');
$('#leftShadow').show('blind');
$('#rightShadow').show('blind');
$('#feedPreviewSection').show('blind');
feedEditNS.createDataTable(withHeaders);
waitForFileTypePreview = false;
},
// In case of failure
error:function(xhr, ajaxOptions, thrownError) {
// Shows the error message
showError(xhr.responseText);
// Clears the preview section
feedEditNS.clearFilePreviewSection();
waitForFileTypePreview = false;
}
I could not resolve the problem.
So, I ended up combining both calls to one call to a single server side method.
This method returned a JSON object containing both calls answers.
I ran into this exact issue (3'ish years later...) I am still not sure what the real problem is, but as a workaround I ended up using setTimeout() inside my Angular controller.
myApp.controller('myCtrl', function($scope, myRestApi) {
$scope.restCallOne = function() {
myRestApi.callOne().then(
// handle result one
);
};
$scope.restCallTwo = function() {
myRestApi.callTwo().then(
// handle result two
);
};
// loads each time the view is shown
// *** race condition when calling consecutively without a delay ***
//$scope.restCallOne();
setTimeout($scope.restCallOne, 100);
$scope.restCallTwo();
});
I am new to this site and had been successfully using the "HTML5" Cross-origin resource sharing (CORS) to POST data to my server. I just recently tried to include GETs in that as we are trying to have all of our communications be non-reliant on a JavaScript library. In doing so I have run into an odd issue that seems somewhat fixable for Firefox but is still misbehaving in all the WebKit browsers. Essentially anything that returns a status of <200 or >300 is just coming in as a status of 0. This makes it next to impossible to do error handling.
For Firefox, I am able to put a random string on the end of the request to prevent it from being cached; thereby fixing the 304s at least. This however does not work at all for me in Chrome/Safari. Here is a sample of my code:
xhr_request: function(type,url, data, callbacks, form){
var form = (typeof(form)!=="undefined")?form:null;
var xhr = new XMLHttpRequest();
var response;
data = com.ticommunity.obj_to_string(data);
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-TxId", com.ticommunity.keyGen());
xhr.withCredentials = true;
xhr.send(data);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
response = xhr.responseText;
com.ticommunity.comm.request_callback(response, callbacks, form);
}else{`//****this is where the 0 Status keeps coming up***`
response = xhr.status;
com.ticommunity.comm.request_callback(response, callbacks, form);
}
}
}
}
Has anyone else run into something similar and come up with a work-around? Am I just doing something stupid on my end? Any help is greatly appreciated.
EDIT: I realized the 0 is what is supposed to happen per the spec, but I REALLY need to be able to trap for these situations and do some other handling.
I haven't seen this issue specifically, but I wonder if you'd have better luck using a different xhr event, such as xhr.onload. You can trust onload to fire on successful responses, so there's no need to check xhr.status. Here's a complete list of events if you need to trap on something else:
http://www.w3.org/TR/XMLHttpRequest2/#events