How to send an Json in GET method in JavaScript? - javascript

Hi I'm trying to translate a code in python to Javasrcipt.
import requests
url = "myApi"
r = requests.get(url, json = {"from": "default", "to": "default"})
dic = r.json()
I don't know how to do it in Javascript. Please help me!!!!

Try this:
const url = "myApi";
fetch(`${url}?${new URLSearchParams({
from: "default",
to: "default",
})}`)
.then(res => res.json())
.then(result => console.log('myApi response', result))

you can use XMLHttpRequest :
let xhr = new XMLHttpRequest();
let url = "url?data=" + encodeURIComponent(JSON.stringify({"from": "default", "to": "default"}));
xhr.open("GET", url, true);
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.from + ", " + json.to);
}
};
xhr.send();

Related

How do I get JSON response from a route?

I have the following route:
#api_blueprint.route("/cars", methods=["GET"])
#jwt_required()
def get_inventory():
with session_scope():
cars = dbu.list_cars()
return jsonify(CarDetails(many=True).dump(cars))
I have to get the JSON response in a GET method which is a list of cars and insert into my html page.
I'm also not sure whether the code after the comment is true, it was one of my attempts to do something.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
/*get here JSON response from a route somehow*/
document.getElementsByClassName("car_name").innerHTML = info.info[1]
document.getElementsByClassName("car_price").innerHTML = info.info[2]
}
else if (xhr.readyState === 4 && xhr.status !== 200){
alert(JSON.parse(xhr.responseText).message);
window.location.reload();
}
};
xhr.send(null);
}
The response is following:
[
{
"carId": 1,
"name": "Chevrolet",
"price": 3547.14
},
{
"carId": 2,
"name": "Lotus",
"price": 4558.47
},
{
"carId": 3,
"name": "Chevrolet",
"price": 4385.96
}
]
When using XMLHttpRequest the response body can be found in the responseText property of the XMLHttpRequest instance. You've misplaced the position of where you read the response.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
// getElementsByClassName returns an array of elements.
// querySelector returns a single element based on a CSS selector.
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
} else {
// statusText shows the status message of the request.
alert(xhr.statusText);
window.location.reload();
}
}
};
xhr.send(null);
Sidenote. Nowadays we have the Fetch API, which is the modern equivalent of the XMLHttpRequest interface. Though it is useful to know how XMLHttpRequest works, I'd recommend learning fetch as well.
The example below is the fetch equivalent of the code above.
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
fetch(url, {
method,
headers: {
"Content-Type": "application/json"
}
}).then(response => {
if (!response.ok) {
throw new Error(`Fetching JSON went wrong - ${response.statusText}`);
}
return response.json();
}).then(data => {
console.log(data);
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
}).catch(error => {
alert(error);
window.location.reload();
});

get Id from online hosted Json

I'm trying to get back my jason data that i saved online with the ID that the hosting service set up for me..
const app = new Vue({
el:'#app',
data:{
input:'',
method:'',
status:'200',
timeStart:0,
timeEnd:0,
},
mounted(){
},
methods:{
http_request(){
const url = 'https://' + this.input;
const currentDate = new Date();
this.timeStart = currentDate.getTime();
axios.get(url)
.then(res => {
let parser = document.createElement('a');
parser.href = url;
const protocol = parser.protocol;
const hostname = parser.hostname; // => "example.com"
const pathname = parser.pathname; // => "/pathname/"
const status = res.status;
const method = this.method;
console.log(status, method);
var resp = {
"status": status,
"errors": {},
"data": {
"method": method,
"protocol": protocol,
"hostname": hostname,
"pathname": pathname,
}
}
var response = JSON.stringify(resp);
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("POST", "https://api.jsonbin.io/v3/b", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);
const currentDate = new Date();
this.timeEnd = currentDate.getTime();
console.log((this.timeEnd-this.timeStart)/1000);
console.log(resp)
I'm able to save the json so far on https://jsonbin.io/... and it looks like this:
BIN ID: 6069e05f8be464182c5881f0
{
"status": 200,
"errors": {},
"data": {
"method": "get",
"protocol": "https:",
"hostname": "my-json-server.typicode.com",
"pathname": "/lalith1403/jsonemaillist/list"
}
}
the BIN ID is the unique ID that I need in order to show only the desired jason data.. I saw it in the response metadata but I cannot fina a way to get it..
this is the response after the json is saved:
{"record":{"status":200,"errors":{},"data":{"method":"","protocol":"https:","hostname":"my-json-server.typicode.com","pathname":"/lalith1403/jsonemaillist/list"}},"metadata":{"id":"6069e6a07d0d5e1833cee3f9","createdAt":"2021-04-04T16:17:36.929Z","private":true}}
My idea is then to make a new call with the Id attached to the url in order to get the unique data but I could be wrong..
Thx for your support
Based off their documentation, you'd definitely be able to do this! As part of the URL for the read request, you just need to do a GET request on the following URL: https://api.jsonbin.io/v3/b/<BIN_ID>/latest (you may have been missing this "latest" end of the URL, which specifies which version of the BIN_ID you want - the 1st version, 2nd version after it's been updated, 3rd, etc. Latest will just get the most recent one, which I assume is what you want.
That could look something like this:
let id = "assigned id here"
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("GET", "https://api.jsonbin.io/v3/b/" + id + "/latest", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);

How to convert ajax request from jQuery pure js?

I need to convert this jquery ajax to Javascript.
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf("\"title\":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace("\"", "");
response1 = response1.replace("\"", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
I was googling a lot but I don't how can I push my data by this url in pure js.
If someone knows how to do this, please help.
Here is the sample.
const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// create a JSON object
const json = {
"email": "abc#example.com",
};
// open request
xhr.open('POST', '/subscribes/emailSubscribe');
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(JSON.stringify(json));

How to get all Files Save in Dropbox to my HTML Page

i have save Images in Dropbox using Javascript like that
document.forms.newsletter.addEventListener('submit', function
cb(evt) {
//evt.preventDefault()
// API key from here: https://dropbox.github.io/dropbox-api-v2-
explorer/#files_upload
// need to consider how this gets secured
var TOKEN = ''
var dir = 'blackground/'
var file = document.getElementById('file').files[0]
var promise = new Promise(function (resolve, reject) {
// Dropbox requires application/octet-stream
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
}
else {
reject(xhr.response || 'Unable to upload file');
}
};
xhr.open('POST',
'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + TOKEN);
xhr.setRequestHeader('Content-Type', 'application/octet-
stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
path: '/' + dir + file.name,
mode: 'add',
autorename: true,
mute: false
}));
xhr.send(file);
})
promise
.then(function (result) {
// Save dropbox response to form
document.getElementById('dropbox').value =
JSON.stringify(result)
// Submit form on successful upload
evt.target.submit()
})
.catch(function (err) {
console.log('a');
})
return false
})
It works fine. But i want to retrieve each Image using Javascript and ajax to display it in my Web Page. How to make it?
I read this Documentation https://www.dropbox.com/developers-v1/core/docs#files-GET that we can make it with Get Verb.
I have make a Get for the API to get All Image like so
$.ajax({
method: "GET",
url: "https://content.dropboxapi.com/1/files/auto/blackground",
dataType: "json",
ContentType:"application/octet-stream",
Authorization:"Bearer token"
});
i get this Error
{error: "Authentication failed"}
error
:
"Authentication failed"
blackground is the folder where are all the Images
Something can help please
It works fine now. I make it like so. Token is my Token for Dropbox.
var token = '';
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var imageUrl = (window.URL || window.webkitURL).createObjectURL(xhr.response);
// display, assuming <img id="image"> somewhere
document.getElementById('image').src = imageUrl;
// download via the download attribute: limited browser support
var a = document.createElement('a');
//a.download = 'test.png';
//a.href = imageUrl;
//a.click();
}
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({ path: '/blackground/blackground_logo.jpg' }));
xhr.send();

nodejs xhr POST

I am using nodejs and trying to make a POST command to a server. I am also using node-xmlHttpRequest (driverdan's module). I am having issues with the content-type and get the error:
{
"response":{
"errorCode":"UNKNOWN_ERROR","message":"Content type
'text/plain;charset=UTF-8' not supported","detail":"Content type
'text/plain;charset=UTF-8' not supported"
},"version":"1.0"
}
I need the content-type to be JSON, not text. I have tested the code with GET and it works fine.
Here is my code:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var sys = require('util');
var json_text2 = { "username": "admin","password": "-----" };
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
//- var xmlHTTP = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState === 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("POST",apic_url,true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Accept","application/json");
xhr.responseType = 'JSON';
xhr.send(JSON.stringify(json_text2));
app.locals.apic_nd = xhr.responseText;
Any ideas?
Thanks to jfriend00 I got it working (not sure how to upvote his comment. But here is the code I used:
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
var request = require('request');
var options = {
url: 'https://'+apicem_ip+'/api/v1/ticket',
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: '{ "username": "admin", "password": "----"}'
};
function callback(error, response, body) {
console.log("callback function");
if (!error) {
var info = (JSON.parse(body));
console.log(info);
console.log("status 200");
}
else {
console.log(JSON.parse(body));
}
}
request.post(options, callback);

Categories

Resources