I have this html + script code:
<html>
<head>
<title>Curriculum</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
function myFunction() {
url: 'https://www.fulek.com/data/api/supit/curriculum-list/hr',
type: 'GET',
contentType: 'application/json'
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254'
},
success: function (result) {
console.log(result);
},
error: function (error) {
}
}
</script>
</head>
<body>
<td><button type="button" onclick="myFunction()">Delete</button></td>
</body>
</html>
and for some reason the fetch call doesn't work. I got the token when I logged in and got the data from the API:
Here is the error I got for some reason: I have tried a few things but I can't really get it right as I almost dont have experience in JS.
First, I'd recommend learning how promises & async/await work in Javascript before working with APIs.
The problem with your code is two-fold:
You aren't returning anything from the function.
You structured the response as an object. However, the object wasn't placed within curly braces { }.
I fixed the function in the snippet below. Hope this helps:
<html>
<head>
<title>Curriculum</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button type="button" onclick="getData()">Delete</button>
<script src="./testing.js"></script>
<script>
async function getData() {
const response = await fetch("https://www.fulek.com/data/api/supit/curriculum-list/hr", {
method: "GET",
headers: {
"Content-Type": "text/plain;charset=UTF-8",
Authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254",
},
});
const data = response.json()
return data.then(response => console.log(response.data));
}
</script>
</body>
</html>
Related
I have created a database in Kinvey and I am trying to load the data with a onclick event on a button. I tried to console.log my response from the promise to see if I will get the object back, but instead of an object it gives me this error:
error: "The Authorization header in your request is malformed. An Authorization header should contain two parts separated by a space: a type (Basic or Kinvey) and a base64-encoded auth string.
What is wrong with my GET request and why does it return this error, since I already have an Authorization header?
here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Blog</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<h1>All Posts</h1>
<button id="btnLoadPosts" onclick="attachEvents()">Load Posts</button>
<select id="posts"></select>
<button id="btnViewPost">View</button>
<h1 id="post-title">Post Details</h1>
<ul id="post-body"></ul>
<h2>Comments</h2>
<ul id="post-comments"></ul>
<script src="./blog.js"></script>
</body>
</html>
and my JavaScript:
function attachEvents() {
const URL = 'https://baas.kinvey.com/appdata/kid_Sy8W2Z0Y7';
const USERNAME = 'Peter';
const PASSWORD = 'p';
const BASE_64 = btoa(USERNAME + ':' + PASSWORD);
const AUTH = {"Authorization" : 'Basic' + BASE_64};
$('#btnLoadPosts').on('click', loadPosts);
function loadPosts() {
$.ajax({
method: 'GET',
url: URL + 'posts',
headers: AUTH
}).then(function(response) {
cosole.log(response);
}).catch(function(error) {
console.log(error);
})
}
}
Did you forget to add a space after Basic in the authorization header?
I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.
Hey guys I am new with this json syntax and I have one problem.
I made function that gets data from remote server in json like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
function getStates(value) {
var data = {
q: value
}
$.ajax({
url: 'https://something.hr/api/search',
method: 'GET',
headers: {'Accept': 'application/json'},
data: data
}).done(function(data) {
//do something with data I returned to you
console.log("success")
console.log(data)
}).fail(function(data) {
//doSomethingWith the data I returned to you
console.log("fail")
console.log(data)
});
};
</script>
</head>
<body>
<input type="text" onkeyup="getStates(this.value)" >
<br>
<script>
</script>
</body>
</html>
My problem is that I know how to get object in console log, but i wish to get that object in html, like in some box, than click on it and open his data(name, id, adress etc.)
var httpManager = (function() {
var getData = function(value) {
$.ajax({
url: 'https://api.github.com/users/zixxtrth',
method: 'GET'
}).done(function(data) {
//do something with data I returned to you
jQuery('#avatar').attr('src', data.avatar_url);
jQuery('#name').html(data.name);
jQuery('#username').html(data.login);
}).fail(function(data) {
//doSomethingWith the data I returned to you
alert('No Data');
});
};
return {
getData: getData()
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<img src='' id='avatar' width='200' height='200' />
<h1 id='name'></h1>
<h2 id='username'></h2>
I was playing around with the WordPress Rest API, and I was downloading this plugin called WP OAuth Server (by Justin Greer), and I have built my own OAuth connection.
I have one problem: I get Error 400, and it says: The grant type was not specified in the request.
Here is my code so far:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<div id="result"></div>
<!--<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>-->
<script type="text/javascript" src="assets/js/app.js"></script>
</body>
</html>
JavaScript:
/**
* OAUTH 2 LOGIN
*/
+function () {
var $CLIENT_CODE = 'fc8uhbwlo4niqhngrjsdl3tbp3cndpidfs61w77g';
var $CLIENT_ID = 'llsfdwZzO7qVHBzM4nhfcq1jFW2L8O';
var $CLIENT_SECRET = 'auaCKn8JWXQmSyYrl3PDi23klIhotp';
var $AUTHORIZATION_ENDPOINT = 'http://domain.dev/oauth/authorize';
var $TOKEN_ENDPOINT = 'http://domain.dev/oauth/token';
$.ajax({
url: $AUTHORIZATION_ENDPOINT + '?client_id=' + $CLIENT_ID + '&client_secret=' + $CLIENT_SECRET + '&response_type=code',
}).done(function (url) {
$('#result').html(url);
fetchSomething();
}).fail(function (errorThrown) {
console.log("Error" > errorThrown.responseText);
})
function fetchSomething() {
$.ajax({
type: 'POST',
url: $TOKEN_ENDPOINT + '?grant_type=authorization_code&code=' + $CLIENT_CODE,
}).done(function (success) {
console.log(success);
}).fail(function (error) {
console.log(error);
});
}
}();
CodePen
This was my solution
$.ajax({
url: 'http://' + domain + '?oauth=token',
type: 'POST',
data: {
grant_type: grantType,
code: code,
client_id: clientID,
client_secret: clientSecret,
redirect_uri: redirect
}
}).done(function (token) {
console.log(token);
}).fail(function (fail) {
console.log(fail.responseJSON.error);
});
I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>