I made a HTML5 app, which accessess JSON data from a web service. The app works fine when opened in a browser on desktop computer, but when it is "phonegapped" into Android application it is not working. I have added following line on the PHP server to enable CORS:
header("Access-Control-Allow-Origin: *");
Following is the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="images"></div>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function onMyClick() {
console.info(new Object("Hello"));
var url = 'http://example.com/mobile/index.php?tag=getAllById&catid=60';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.info(responseText);
// process the response.
};
xhr.onerror = function() {
console.info('There was an error!');
};
xhr.send();
console.info(new Object("Hello 4"));
}
</script>
<input type="button" value="OK" onclick="onMyClick()"/>
</body>
</html>
Not working as Android app means that I am getting, "There was an error!" message as the above line in onerror event prints, instead of the JSON data as response text, in the console of eclipse. Please could anyone help me get this working as Android application also.
With the above example I can't see what is wrong but there are multiple possibilities.
The domain you are accessing might not be white listed in your config.xml? To allow everything include the following:
<access origin="*" />
See docs about white list for more info here
Another thing which comes to mind, your app needs internet connection to work, do you have the required permissions setup in AndroidManifest.xml?
You need to find the<uses-permission android:name="android.permission.INTERNET" /> declaration.
Related
I am trying to conenct to any external server in order to display server time instead of the machine time in JavaScript.
I have tried reading
How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?
, Understanding XMLHttpRequest over CORS (responseText)
, and How does Access-Control-Allow-Origin header work?
but am very limited in knowledge for this subject, so am confused on how to implement the suggestions to get access to a server time.
I am still getting the error:
Access to XMLHttpRequest at 'https://www.stackoverflow.com/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And don't know how to fix it. This is the current code that I have:
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server date/time</title>
<script language="javascript" src="main.js"></script>
</head>
<script language="javascript">
document.write("Server time is: " + date);
</script>
<body>
</body>
JavaScript:
var xmlHttp;
function serverTime(){
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
// use CPU time.
alert("Using CPU Time");
}
}
}
xmlHttp.open('HEAD',"https://www.stackoverflow.com",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
return xmlHttp.getResponseHeader("Date");
}
var st = serverTime();
var date = new Date(st);
Ideas on what I am doing wrong and what I can do to get the server time? Thanks!
I am getting a response body with raw response, which is supposed to respresent a png image. My question is how to decode this and make it a renderable.
PS: when I am use postman to test this, I realized that Postman can render this raw string, and I am wondering how it does it.
�PNG
IHDR�X:�(� pHYs���o�d
IDATx���\�w����v,J�L�2b�_٬�N��d��0|�cmDN�6�y.�q�{�Iӌ�hsnNcl��g~/;"vʯ�m�('}�Q9��q�P(G:�������z=���q��|=_�\�p�""""""�p�w""""""b
�""""""J�PDDDDD�A)������8(B�#("""""�EDDDDD���������R
qP
�""""""J�PDDDDD�A)������8(B�#("""""�EDDDDD���������R
[...]
After a few hours of googling, I finally figured out the issue:
Essentially, the response from my REST call actually contains blob type of the png image. So to properly render it, we don't have to base64 the blob, instead it is natively supported by html5. The problem I was facing is that this blob is not supported by jQuery ajax call, hence higher level libraries like axios does NOT support it either.
For simplicity, to demo how this works, I would use jQuery:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Blob image/png demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="invokeBlob">
<input type="submit" value="Invoke It!">
</form>
<!-- the result of the blob will be rendered inside this div -->
<div id="imgcontainer"></div>
<script>
// Attach a submit handler to the form
$( "#invokeBlob" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var url = "https://YOUR-DOMAIN/charts";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("Authorization", "Bearer XXX-YOUR-JWT-TOKEN")
xhr.setRequestHeader("Accept", "image/png");
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
$("#imgcontainer").html(img);
}
}
xhr.send();
});
</script>
</body>
</html>
I have the following code which I can't figure out why it didn't work:
<script>
var request = new XMLHttpRequest();
request.open("GET", "textfile.txt", true);
request.onreadystatechange = function() {
if(request.readyState===4) {
alert(request.responseText);
}
};
request.send(null);
</script>
<html>
<head>
</head>
<body>
</body>
</html>
I'm sure that I have the file name "textfile.txt" in the same directory as the html file. What I get is only an empty javascript alert but I can't display the text file text.
EDIT:
I noticed that I get the following error when I viewed the developer tools this error at the request.send(null) line:
XMLHttpRequest cannot load file:///D:/textfile.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
You need a web server, such as Nginx, Apache and IIS and then put your HTML file and textfile.txt in the same domain.
Try:
<html>
<head>
</head>
<body>
<script>
var request;
if (window.XMLHttpRequest) {
// code for modern browsers
request = new XMLHttpRequest();
} else {
// code for IE6, IE5
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("GET", "textfile.txt", true);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
else //error handling
{
console.log("Error", this.statusText);
}
};
request.send();
</script>
</body>
</html>
I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts.
Looks like I messed up, but I can't see where. What should I change to make it work?
If you can use xhr2, you can learn stuff from this tutorial and rewrite your code to something like this:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
If you send request to another domain, you may get error even if it exists, if the target server has Same-Domain-Policy restriction (default). If the target server is on another domain, it must send header
Access-Control-Allow-Origin: *
So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.