Why is this JSON query not working? - javascript

I am so confused at the moment, as to why this will not work.
<div id="result" style="color:red"></div>
and
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();
});
};
getJSON('https://www.eobot.com/api.aspx?coin=DOGE&json=true').then(function(data) {
alert('Your Json result is: ' + data.DOGE); //you can comment this, i used it to debug
result.innerText = data.DOGE; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
It's exactly the same as: http://jsfiddle.net/RamiSarieddine/HE2nY/1/ but yet that works..
Edit: For the sake of clarity, the script is supposed to take the content at the url (within the DOGE element) and display it within
<div id="result" style="color:red"></div>

I tested it and i get below error, Which means when you try to get the json from https://www.eobot.com/api.aspx?coin=DOGE&json=true , its blocked from receiving the data due to cross browser rules.
No 'Access-Control-Allow-Origin' header
How to fix it ,
You must own https://www.eobot.com and run this script on www.eobot.com , Else you cant get the json due to cross domain policy.Ask the owner to whitelist your domain in his allow-origin header.

Related

Why does 1 out of 10 of my requests returns CORS error in the browser

I currently have a script that makes an ajax request using XMLHttpRequest(). The essence of the script is to keep track of certain analytics and here's how it was implemented.
Adds an event listener and sends data to start_tracking_analytics script
document.addEventListener('DOMContentLoaded', function(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/start_tracking_analytics.php?key='+tracker_key;
//host name
var host = location.protocol + '//' + location.hostname
//send data
sendAnalytics(url, host);
setTimeout(function(){
setInterval(function(){
try{
sendUpdateAnalytics();
}catch(e){
}
}, 7500);
}, 1000);
}catch(e){
}
});
Here's how the sendAnalytics function is implemented
function sendAnalytics(url, host){
try{
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onerror = function() {
// Error code goes here.
};
xhr.send();
}catch(e){
//...
}
}
Here's how sendUpdateAnalytics was implemented. Note: This gets triggered at intervals
function sendUpdateAnalytics(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/end_tracking_analytics.php?id='+tracker_session_id;
//current host
var host = location.protocol + '//' + location.hostname
//send the data
sendData(url, host);
}catch(e){
}
}
Now, to the backend (response) script. i.e - start_tracking_analytics.php && end_tracking_analytics.php
On both scripts, I had this headers set
//GET variables
$host = $_GET["host"];
$key = $_GET["key"];
//set header for CORS
header("Access-Control-Allow-Origin: $host");
header("Access-Control-Allow-Credentials: true");
//I Do all of my computations here and echo an integer
echo 1;
The problem: 1 out of 10 requests made to end_tracking_analytics returns CORS error
Access to XMLHttpRequest at 'https://subdomain.domain.com/end_tracking_analytics.php?id=1&host=https://www.hostUrl.com&key=XXXXX' from origin 'https://www.hostUrl.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I really do hope this is explanatory and will be happy to provide more details if it's not. Any idea why this could be happening?

xhr does not get invoked from js

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Add header to http request

My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);
You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);

Sending cross-domain ajax requests without jQuery

I have the following code:
function ajax(callback, requestString){
console.log("basic ajax sending");
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText); //we got a response
}
}
xmlhttp.open("GET", requestString, true);
xmlhttp.send();
}
//Here: code to be able to use that function repeatedly.
it works great if used on my node.js server's domain, problem is that I am developing an API, and requests have to be sent cross-domain. These requests(requestString) are just one string that is formatted something in the likes of: "http://example.com/r?a=a" + "&b= b" if that matters. I get the following error: XMLHttpRequest cannot load. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. I did see a solution with jQuery and jsonP but I don't want to shove jQuery to my clients, so I have to find a good solution...
Thank you for your time!
But jsonP can work without jQuery. For example:
var CallbackRegistry = {};
function scriptRequest(url, onSuccess, onError) {
var scriptOk = false;
// generating JSONP function name
var callbackName = 'cb' + String(Math.random()).slice(-6);
// add name in url
url += ~url.indexOf('?') ? '&' : '?';
url += 'callback=CallbackRegistry.' + callbackName;
CallbackRegistry[callbackName] = function (data) {
scriptOk = true;
delete CallbackRegistry[callbackName];
onSuccess(data);
};
function checkCallback() {
if (scriptOk) return;
delete CallbackRegistry[callbackName];
onError(url);
}
var script = document.createElement('script');
// for IE
script.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
this.onreadystatechange = null;
setTimeout(checkCallback, 0);
}
}
script.onload = script.onerror = checkCallback;
script.src = url;
document.head.appendChild(script);
}
Now you can get response through cross domain just call
function afterSuccess(data) {
alert('Success' + data);
}
function afterError(data) {
alert('Error' + data);
}
scriptRequest(url, afterSuccess, afterError);
Well, on the server side you could change the Access-Control-Allow-Origin for the end point to Access-Control-Allow-Origin: *, ...note this will match anything. Depending on your server framework there is definitely a method to whitelist certain urls to access your endpoint. Hope that helps

Signature does not match s3 GET object

I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance

Categories

Resources