How to Connect to a Time Server JavaScript - javascript

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!

Related

Can't Access to API using jQuery

I am using pCloud Api to get download link form the request. It is a GET request. When I request form browser I can get a response. But when I use jQuery I get a response code result : 7010
Api Request URL : https://api.pcloud.com/getpublinkdownload?code=8eM7
I get this response when requesting from browser:
{
"result": 0,
"expires": "Mon, 07 Aug 2017 00:12:50 +0000",
"dwltag": "aftsTab2SLkC4MDXRdp6Am",
"path": "\/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7\/image%20%286%29.jpg",
"hosts": [
"p-def2.pcloud.com",
"c166.pcloud.com"
]
}
I need this hosts and path to generate the download link. I just need this -https://c166.pcloud.com/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7/image%20%286%29.jpg
I have to use jQuery/JavaScript to get this response. I tried PHP file_get_contents(); it works but this link will work only form the ip address you request for. So, I must use JQ/JS.
My Code:
$(document).ready(function(){
function httpGet(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
console.log(httpGet("https://api.pcloud.com/getpublinkdownload?code=8eM7"));
});
Thanks for trying to help me.
It seems pCloud server is checking referrer.
In most case, servers will refuse the accesss not coming from itself.
Only web browsers arriving from a small set of approved (login) pages are given access; this facilitates the sharing of materials among a group of cooperating paysites from https://en.wikipedia.org/wiki/HTTP_referer
In following html, script ran and got image url successfully, but browser raised error when it was trying to load image.
<html>
<head>
</head>
<script
src="http://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<body>
<h1>Load Image from pCloud </h1>
<img class="loading">
<script>
$(document).ready(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText){
var host = JSON.parse(this.responseText).hosts[0];
var path = JSON.parse(this.responseText).path;
}
$(".loading").attr("src", "https://" + host + path);
}
};
xhttp.open("GET", "https://api.pcloud.com/getpublinkdownload?code=8eM7", true);
xhttp.send();
});
</script>
</body>
</html>

Phonegapped Android application not working as compared to HTML5 app

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.

POST JSON using JavaScript

I am trying to do http post using JavaScript but something is going wrong..
I already searched a bit, and found two snippets but none is working.
The first attempt:
<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id) {
var xmlhttp = new XMLHttpRequest();
var url = "http://10.21.6.128:1234/test/test2/teste3/teste4";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});
xmlhttp.send(parameters);
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
In this attempt, there is no JSON being thrown, at my server I get a null input.. I used fiddler to check it, and nothing is being posted..
I searched a few more and found this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "http://10.21.6.128:1234/teste/teste2/teste3/teste4",
type: "POST",
data: {"Test":"2222","Code":"OP1","Partner":"Test","Prod":"Prod"},
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
In this case I get a bad request, error 400.
Can someone help me?
Thanks alot in advance ;)
It appears the POST request never gets sent due to Same Origin Policy. Your fiddler screenshot shows an OPTIONS request, which is expected in a cross domain situation. The OPTIONS request is used to find out if the target server supports Cross Origin Resource Sharing (CORS). This is known as a preflight request.
In order for a request to be considered "same domain", the protocol, domain and port all must match.
If you control the target server, you can enable CORS by outputting the response header:
Access-Control-Allow-Origin: *
Note: the * denotes all domains are permitted, you can narrow it to a specific domain if more suitable.
Also, the second code sample in the question will never send JSON, regardless of CORS.
w3.org/cors
Add jQuery to first example and try following,
var parameters = $.param({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});
instead of,
var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});

XMLHttpRequest connection check

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: *

Ajax Pull Content From another webpage

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.

Categories

Resources