I tried to download a file from Dropbox using Core Api with javascript.
Here is the method I have written.
function downloadFile(path) {
var url = "https://api-content.dropbox.com/1/files/auto/"+path;
var result;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.send(path);
}
But I am always getting the status as 400. Don't know whats wrong. I got this below HTML as response.
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx</center>
</body>
</html>
Edit 1 :
var url = "https://api-content.dropbox.com/1/files/auto/" + path;
var result;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("access_token",token);
xhr.send();
Related
I have a problem with uploading a file to a node server via HTML. In the page I have this input:
<input type="file" id = "csvFile" />
<input type="submit" name="submit" onclick="send_data()" />
Then I have the send_data function that looks like this:
function send_data(){
let file = document.getElementById("csvFile");
const xhr = new XMLHttpRequest();
xhr.open("GET", file, true);
xhr.setRequestHeader("Content-type", "text/csv");
xhr.onreadystatechange = () =>{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
console.log("done");
}
xhr.send();
}
Here there is the first problem, because the arrow function of the ready state never executes.
In any case, it's the first time I do something like this, so I don't know how I can make sure that my server gets the file and processes it. Can someone help me?
This should do the trick:
let file = document.getElementById("csvFile").files[0];
let xhr = new XMLHttpRequest();
let formData = new FormData();
formData.append("csvFile", file);
xhr.open("POST", '${your_full_address}');
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send(formData);
Refer: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
I m trying to make a post request to the server by clicking a button
FYI this code is in HTML file
<button onclick="vf()" >click</button>
<!---script---->
<script>
function vf(){
var http = new XMLHttpRequest();
///aServe= anyserver
var url = 'aServer';
var myName = 'name=me';
http.open('POST', url, true);
///setting header
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseURL);
}
}
http.send(myName);
};
</script>
I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.
How can I test user credentials using javascript?
I tested the good URL with app_code and app_id. When they are ok all other requests seem to be ok too.
You can do it so e.g.:
var app_id = "test_app_id";
var app_code = "test_app_code";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4 ) {
if(this.responseText.indexOf("France") != -1){
console.log("Credentials is OK");
}else{console.log("Wrong credentials");}
}
});
xhr.open("GET", "https://geocoder.api.here.com/6.2/geocode.json?app_id="+ app_id+"&app_code=" + app_code + "&country=FRA");
xhr.send();
I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload