Consuming api using Javascript - javascript

I have been struggling to render a data object returned by an API request on an HTML page, however it keeps displaying the string object on the HTML page. Another problem is that I am not able to make use of the data object returned by the API request outside of the API function in Javascript. See the code below:
The API request, the console.log(data) outside the API function does not work
var params = {
// Request parameters
};
$.ajax({
url:
"https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
$.param(params),
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key",
"ef4ed92186214c868a59d97c3b353661"
);
},
type: "GET",
// Request body
data: "{body}",
})
.done(function (data) {
console.log(data);
document.getElementById("data").innerHTML = data.results;
})
.fail(function () {
alert("error");
});
});
console.log(data);
The HTML Page
<html>
<head>
<title>JSSample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="data"></div>
</body>
</html>

You need to pass in a callback function to handle the returned data.
function do_request(cb, cb_fail) {
var params = {};
$.ajax({
url:
"https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
$.param(params),
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key",
"ef4ed92186214c868a59d97c3b353661"
);
},
type: "GET",
// Request body
data: "{body}",
})
.done(cb)
.fail(cb_fail);
}
function cb(data) {
// you now have access to the data here
document.getElementById("data").innerHTML = JSON.stringify(data.results)
}
function cb_fail(error) {
console.log(error)
}
do_request(cb, cb_fail)

Related

Laravel 8 and ajax

Never used ajax before and I'm quite new to Laravel as well.
I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.
function myFunction() {
var x = document.getElementById("frm1");
//console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";
if (
!details.match(
/\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
)
) {
document.getElementById("personValidation").innerHTML =
"Your search does not match the required format";
return;
}
$.ajax({
url: "/api/pnc/person",
type: "POST",
dataType: "json",
success:function(amount) {
console.log(amount);
}
});
``` Javascript
public function person(Request $request)
{
$request->validate([
'search' => 'required'
]);
return "test";
}
You need to Follow 3 steps for Ajax Request-
1. Setup Ajax Header bottom of your code. I mean before </html> add below code.
<script>
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
2. If you don't use Header Then you can use.
<script>
$(document).ready(function () {
$("#your_form_id").submit(function(e) {
var details = $('#details_input_id').val();
if(your_condition){
$.ajax({
url: "api/url",
type: "post",
data: {"_token": "{{csrf_token()}}", 'details':details},
success:function(data){
//Your response
if(data){
consol.log("Print what you want to print");
}
}
});
}else{
alert("Your search does not match the required format")
}
});
});
</script>
3. Your Route will be like ajax url
Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

javascript how to get json data with api call to redirected url

I'm fetching json data from gltich API.
https://wind-bow.gomix.me/twitch-api/users/freecodecamp
When I go to that link, the url redirects to another domain
https://wind-bow.glitch.me/twitch-api/users/freecodecamp
(domain name change from gomix.me to glitch.me)
Using postman for both HTTPs request, I get the same JSON data. However, both don't produce the same results when using jQuery .getJSON method
$(document).ready(function() {
$.getJSON("https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) {
console.log("Gomix.me URL", data1); // nothing outputted
});
$.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) {
console.log("Glitch.me URL", data2); // expected data outputted
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Is it possible to get JSON data through a URL that will be redirected gomix.me, or am I only able to use the final endpoint only glitch.me?
Gomix request is blocked by CORS policy. You can use this heroku app to bypass it: https://cors-anywhere.herokuapp.com/.
$(document).ready(function() {
$.getJSON("https://cors-anywhere.herokuapp.com/https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) {
console.log("Gomix.me URL", data1); // now it works
});
$.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) {
console.log("Glitch.me URL", data2); // expected data outputted
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you use $.ajax with dataType: 'jsonp' it helps you.
$(document).ready(function() {
$.ajax({
url: "https://wind-bow.gomix.me/twitch-api/users/freecodecamp",
type: 'GET',
dataType: 'jsonp',
success: function(data1) { console.log("Gomix.me URL", data1);}
});
});

Project Oxford - HTTP 404 when calling Computer Vision API through Javascript

I am trying to get JSON data from Microoft Project Oxford through a API call. I followed the API reference but when I make a call I get a 404 error.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "All",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/analyses&" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","0000000000000000");
},
type: "POST",
// Request body
data: '{ "Url": "http://www.sweetheartmotors.ca/sites/default/files/audi_PNG1736.png" }',
})
.done(function(data) {
alert("success");
//display data
console(data);
})
.fail(function() {
alert("error");
});
});
</script>
What is stopping me from making the call?
You need to change the URL to end in a question mark, rather than an ampersand: https://api.projectoxford.ai/vision/v1/analyses?
Unfortunately most of the samples on the projectoxford.ai site contain this error.

Categories

Resources