How can I make a REST XMLHttpRequest call from AFrame while using 8th Wall Web? - rest

I am using 8th Wall SDK and trying to call an API. When I am attempting to do that from AFrame.registercomponent onclick method, the request is not getting sent.
I am new to AR. When I tried adding an alert messages for xhttp, it's empty.
What am I missing?
Is there an alternative to this?
By the way, I tried doing this with with an AR marker using Awe.js and it worked fine.
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.status == 200) {
this.responseText;
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
}
// END
video.play();
}
}
I expect the call is made successful to the API.

The xhttp.open and xhttp.send calls are inside the onreadystatechange handler so it will not get sent. Something like this should work:
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.status == 200) {
alert(this.responseText);
}
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
// END
video.play();
}
}

Related

Reactjs: Disable button to avoid double submission, then enable button once request is complete (response received)

I'm creating a reactjs form that submits a form (with field data and a file).
When the Submit button is clicked, its triggers the onClick event that invokes some handleFormSubmission method.
This handleFormSubmission method first disables the button, then creates an XMLHttpRequest that sends the form data away. It might take some moment to the response to come back, and until then the button remains disable.
But once the response is theree, be it successful (code 200) or fail (code 500), I want the Submit button to be re-enabled so user can do another submission.
For the disabling, I simply set the state isFormSubmitted to true, and bind it to the button's disabled property. How could I then re-enable it?
handleFormSubmission() {
this.setState({
isFormSubmitted: true
});
// stuff...
let xhr = new XMLHttpRequest();
xhr.open('POST', '/some-uri, true);
this.setOnLoad(xhr);
xhr.send(formData);
}
setOnLoad(xhr) {
xhr.onload = function(){
if (xhr.status == 200){
// request succeeded...
} else if (xhr.status == 500){
// request failed
} else {
// anything else..
}
};
}
You can check the state isFormSubmitted and disable the submit logic:
handleFormSubmission() {
if (this.state.isFormSubmitted) return;
this.setState({
isFormSubmitted: true
});
// stuff...
let xhr = new XMLHttpRequest();
xhr.open('POST', '/some-uri, true);
this.setOnLoad(xhr); xhr.send(formData);
}
setOnLoad(xhr) {
xhr.onload = function() {
if (xhr.status == 200) {
// request succeeded...
} else if (xhr.status == 500) {
// request failed
} else {
// anything else..
}
this.setState({
isFormSubmitted: false
});
};
}

Page Facebook Access Token

I'm working on a website in which displays the reviews/ratings of a facebook page through the GRAPH API using JS and JSON calls to have the ratings. But there would be no way to read these assessments without an access token, since they are public information? Or one that lives more than 60 days.
<script id="erasable" type="text/javascript">
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
`enter code here`});
};
getJSON('https://graph.facebook.com/FACEBOOK-PAGE-ID/ratings?access_token=PAGE-ACCESS-TOKEN').then(function(data) {
//some html pos-processing
}, function(status) { //error detection....
//alert('Something went wrong.');
});
</script>

for loop not waiting for function to end

I have 5 links on a page and i have to check if all are links are working or not. Here is the code
// iterate through each link and check if ti works.
for(var i=0; i < 5; i++) {
var ifLinkWorks = verifyLinkWorks(links[i]);
if(ifLinkWorks){ OK }
else{ error }
}
This is verifyLinkWorks function. It opens a link. After it get opened, it checks if the page is loaded properly
function verifyLinkWorks(link) {
return winjs.Promise(function(complete) {
link.click();
// wait for page to load
return winjs.promise.timeout(4000).then(function () {
// check if page is loaded
var islinkOK = IsPageLoaded();
complete(islinkOK); // i want verifyLinkWorks to return this value
});
});
}
After reaching link.click(), it is not waiting for page to load. Instead it jumps to the if condtion in outer for loop (which makes linkWorks = undefined therefore,gives Error). How to make it wait in the verfifyLinkWorks function.
Thanks in advance...
You'll need to wait for the results of each promise, either all at once, or individually. As the actions are all async in nature, the code can't wait, but it can call a function when it completes all of the work.
Here, I've created an array which will hold each Promise instance. Once the loop has completed, the code waits for all to complete, and then using the array that is passed, checking the result at each index.
// iterate through each link and check if it works.
var verifyPromises = [];
for(var i=0; i < 5; i++) {
verifyPromises.push(verifyLinkWorks(links[i]));
}
WinJS.Promise.join(verifyPromise).done(function(results) {
for(var i=0; i < 5; i++) {
var ifLinkWorks = results[i];
if (ifLinkWorks) { /* OK */ }
else { /* error */ }
}
});
In case the link.click() call fails, I've wrapped it in a try/catch block:
function verifyLinkWorks(link) {
return WinJS.Promise(function(complete, error) {
try {
link.click();
} catch (e) {
complete(false); // or call the error callback ...
}
// wait for page to load, just wait .. no need to return anything
WinJS.Promise.timeout(4000).then(function () {
// check if page is loaded
var islinkOK = IsPageLoaded();
// finally, call the outer promise callback, complete
complete(islinkOK);
});
});
}
If you want to check the validity of a URL, I'd suggest you consider using WinJS.xhr method to perform a HEAD request instead (rfc). With each link variable, you can use a timeout to validate that there's a reasonable response at the URL, without downloading the full page (or switch to a GET and check the response body).
WinJS.Promise.timeout(4000,
WinJS.xhr({
type: 'HEAD',
url: link
}).then(function complete(result) {
var headers = result.getAllResponseHeaders();
}, function error(err) {
if (err['name'] === 'Canceled') {
}
if (err.statusText) {
}
})
);
Ok heres the link to the msdn code sample for win js promise object.
Promise winjs
now going through the code
<button id="start">StartAsync</button>
<div id="result" style="background-color: blue"></div>
<script type="text/javascript">
WinJS.Application.onready = function (ev) {
document.getElementById("start").addEventListener("click", onClicked, false);
};
function onClicked() {
addAsync(3, 4).then(
function complete(res) {
document.getElementById("result").textContent = "Complete";
},
function error(res) {
document.getElementById("result").textContent = "Error";
},
function progress(res) {
document.getElementById("result").textContent = "Progress";
})
}
function addAsync(l, r) {
return new WinJS.Promise(function (comp, err, prog) {
setTimeout(function () {
try {
var sum = l + r;
var i;
for (i = 1; i < 100; i++) {
prog(i);
}
comp(sum);
}
catch (e) {
err(e);
}
}, 1000);
});
}
</script>
you will see the addAsync(3,4).then() function. So all the code is to be kept inside that function in order to have a delayed response . Sorry m using a tab so cannot write it properly.
Also go through link then for winjs promise

iPhone cross-domain ajax request fails

Hi I am creating an application where I used ajax request to populate the List of Items.
It works in PC-Browser but not works in iPhone safari.
What could be the issue in safari? Please Help.
createXMLHTTPHandle:function(url,onSuccess,onError){
var xhttp;
try {
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", url, false);
xhttp.setRequestHeader("Content-Type",
"text/xml;charset=utf-8");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
if(xhttp.status == 200)//clear db and parse
and store new data
{
onSuccess(xhttp.responseText);
}
}
};
xhttp.send();
}
catch(err) {//
if(err=="Error: NETWORK_ERR: XMLHttpRequest Exception 101")
alert("Please check your network connection!");
onError(err);
}
}

Drupal JSON POST from PhoneGap

I am trying to send a POST request to Drupal's Services module & JSON_Server module, however I am getting
{ "#error": true, "#data": "Invalid method " }
Since PhoneGap runs html files from locally on the phone, should i need to worry about JSONP. The issue I have with that is that I must POST data, and JSONP only allows for GET. Any ideas would be helpful. Thanks!
//SEND REQUEST AND CALLBACK FUNCTION
var req;
DrupalService.prototype.request = function(dataObject, callback){
req = false;
var url = DRUPAL_JSON_URL;
var params = "data="+dataObject;
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
console.log(">> "+req.responseText);
}
}
req.open("POST", url, false);
req.send(params);
}
}
So i figured it out, It had to do with conflicting content types
make sure you set it as
Content-Type = application/x-www-form-urlencoded;
var DRUPAL_JSON_URL = "http://myDrupalsSite.com/services/json";
var req;
DrupalService.prototype.request = function(dataObject, callback){
var url = DRUPAL_JSON_URL;
req = false;
var params = "method=system.connect";
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
alert("test " + req.responseText)
console.log("RESPONSE "+req.responseText);
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(params);
}
}