Can't Access to API using jQuery - javascript

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>

Related

Why doesn't ajax show the content of updated JSON?

I am new to JavaScript. What I want to do is sending an ajax request and get the content of a JSON file and simply put it into a div. This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
<script>
document.getElementById("button").addEventListener('click', loadText);
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('text').innerHTML = this.responseText;
}
else if (this.status == 404){
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
</script>
</body>
</html>
And this is users.json:
[
{
"id":1,
"name":"Rick",
"email":"rick#gmail.com"
},
{
"id":2,
"name":"Negan",
"email":"negan#gmail.com"
}
]
This works fine. But, when I manually updated users.json and change it and refresh the browser, the browser does not show the updated json. It still gives me the previous json file. How can I fix it?
It is possible that the browser is responding with a cached response.
Try appending 'timestamp' so that every time a new request would be made to the server to get updated contents.
document.getElementById("button").addEventListener('click', loadText);
function loadText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json?ts=' + Date.now(), true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById('text').innerHTML = this.responseText;
} else if (this.status == 404) {
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
As you have included jQuery in your webpage, I would recommend to use jQuery version of ajax. To disallow the use of the cached results, set cache to false.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
data: jsonDataObject,
cache: false, // Appends _={timestamp} to the request query string
success: function(data) {
// data is a json object.
}
});
try check the disable cache checkbox on network panel of the dev tool.
it might be caused by the cache of your web server
You need to pass header
content_type="application/json"

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Retrieve HTML of ReadMe

Hi so first time working with APIs like this. Anyways, I've been reading up on the GitHub API and came across this:
READMEs support custom media types for retrieving the raw content or rendered HTML.
src: https://developer.github.com/v3/repos/contents/#get-the-readme
Which I believe means that it is possible to retrieve an HTML formatted version of the contents of the README? If so how would I retrieve it using AJAX since the tutorials are all for curl. In the end I want to display a portion of it on my website and would be a lot easier if given in the html format rather then markdown.
The docs say something about: application/vnd.github.VERSION.html
I just don't necessarily know how to use it.
Thanks!
You have to set the Accept header of the HTTP request to application/vnd.github.html.
$.ajax({
url: 'https://api.github.com/repos/just95/toml.dart/readme',
headers: { 'Accept': 'application/vnd.github.html' }
}).done(function(data) {
alert(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
All you need to do is set the Accept header of your HTTPS request. Using cURL for example:
curl -i -H "Accept: application/vnd.github.v3.html" https://api.github.com/repos/github/developer.github.com/readme
In JavaScript,
var apiRoot = 'https://api.github.com';
var myUser = YOUR_USER_HERE;
var myRepo = YOUR_REPO_HERE;
var request = new XMLHttpRequest();
request.open('GET', apiRoot + '/repos/' + myUser + '/' + myRepo + '/readme');
request.setRequestHeader('Accept','application/vnd.github.v3.html');
/* add event listeners... */
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
document.body.innerHTML = request.response;
}
};
request.send();

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

Is there a way to do a http head request and get the time without a server side language

I am trying to do a http head request from the Javascript code to get the server time ...Can I do this from javascript or do I need a server side language to achieve this
Assuming your server sends the Date header (which the RFC says it MUST), sure:
$.ajax('/', {
type: 'HEAD',
success: function(r,status,xhr) {
alert(xhr.getResponseHeader('Date'));
}
});
Or without the use of jQuery, not much more code but possibly less error handling :
function getServerTime() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.getResponseHeader('Date'));
}
};
xhttp.open("HEAD", "/", true);
xhttp.send();
}

Categories

Resources