Display jsonp data from ajax api call - javascript

I am getting a syntax error on inspection when this code is ran. I would like to display the results in the "output" div but there seems to be a translation issue. I have to use jsonp because I am accessing a server that I cannot control.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js" rel="javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" rel="jquery"> </script>
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
dataType: "jsonp",
jsonpCallback: 'callback',
//data: {format: "jsonp"},
//data: JSON.stringify,
success: function( response ) {
console.log( response ); // server response
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
}
});
</script>
CrossDomain:
var proxyJsonp="https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdprSITn45-4UgVJnzp9/exec";
jQuery.ajaxOrig=jQuery.ajax;jQuery.ajax=function(a,b){function d(a){a=encodeURI(a).replace(/&/g,"%26");return proxyJsonp+"?url="+a+"&callback=?"}var c="object"===typeof a?a:b||{};c.url=c.url||("string"===typeof a?a:"");var c=jQuery.ajaxSetup({},c),e=function(a,c){var b=document.createElement("a");b.href=a;return c.crossOrigin&&"http"==a.substr(0,4).toLowerCase()&&"localhost"!=b.hostname&&"127.0.0.1"!=b.hostname&&b.hostname!=window.location.hostname}(c.url,c);c.proxy&&0<c.proxy.length&&(proxyJsonp=c.proxy,"object"===typeof a?
a.crossDomain=!0:"object"===typeof b&&(b.crossDomain=!0));e&&("object"===typeof a?a.url&&(a.url=d(a.url),a.charset&&(a.url+="&charset="+a.charset),a.dataType="json"):"string"===typeof a&&"object"===typeof b&&(a=d(a),b.charset&&(a+="&charset="+b.charset),b.dataType="json"));return jQuery.ajaxOrig.apply(this,arguments)};jQuery.ajax.prototype=new jQuery.ajaxOrig;jQuery.ajax.prototype.constructor=jQuery.ajax;

By the looks of that link, the server is returning JSON, not JSONP. If the API supports it, you should be using CORS instead.
Example:
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});

Related

How can I post data to FastAPI using JavaScript and AJAX?

I am trying to to post some data via a request body to my server and for some reason I am getting a msg: "value is not a valid dict", type: "type_error.dict" error.
The backend (built in FastAPI) is working fine, as I am able to get a proper response when using FastAPI's Swagger UI.
I am quite new to JavaScript and AJAX (I mainly work with Python), so I think the issue must be coming from the AJAX function I setup.
My code
main.py (Backend)
from typing import Union
from fastapi import FastAPI, Form
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:8080",
"http://127.0.0.1:5500",
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str
#app.post("/items_via_request_body")
def read_item_via_request_body(item: Item):
#return {"item_id": item.id, "item_description": item.description}
return {"Hello": "World"}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h1>Hello world</h1>
<button id="request_body_param">Test Request body Parameters</button><br>
<script>
$(document).ready(function(){
// Request body parameters
$("#request_body_param").click(function(){
console.log('request_body_param pushed')
$.ajax({
url: "http://127.0.0.1:8000/items_via_request_body",
type: "POST",
data: {
id: 123,
name: "John",
description: "I am a description"
},
dataType: "json",
success: function(data){
$("#content").html(data);
console.log("SUCCESS: " + JSON.stringify(data));
},
error: function(data){
$("#content").html("Failed to load data. " + JSON.stringify(data));
console.log("ERROR: " + JSON.stringify(data));
},
complete: function(data){
console.log("COMPLETED: " + JSON.stringify(data));
},
});
});
});
</script>
</body>
</html>
Any help is really appreciated!
from fastapi import FastAPI, Request
# code-stack as in question...
#app.post("/items_via_request_body")
def read_item_via_request_body(request: Request):
form_data = request.form()
# ... Data management operations here ...
return form_data

Computer Vision API for javascript not working[Beginner's error]

I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!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() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!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">
var myKey = "6e07223‌​403d94848be20af6f126‌​fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>

My Jstree dont show any folder

I'm trying to create a jstree that is connected to my Dropbox API. I want to show all my folders in my Dropbox to jstree but there's no output and there's no error to it just said that:
XHR finished loading: POST "https://api.dropboxapi.com/1/delta".
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax JS Tree</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/themes/default/style.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
</head>
<body>
<div id="container"></div>
<script>
$(function() {
var fullTree;
var url = 'https://api.dropboxapi.com/2/files/alpha/get_metadata';
var access_token = 'I-pZSjTC4tAAAAAAAAAAl1Wpza91KvV_17XKarAsyEMpC78Ereo9-uO2QVE-Sx0a';
$.ajax({
url: url,
data: fullTree,
method: "POST",
dataType: "json",
beforeSend: function(request) {
request.setRequestHeader("Authorization", 'Bearer ' + access_token);
},
success: function(fullTree) {
$('#container').jstree({
'core': {
"data": fullTree,
"check_callback": true,
},
"plugins": ["themes", "contextmenu", "ui"]
});
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
</body>
</html>
I tried everything including AJAX and jQuery on it but nothing happens.
It seems you put your url variable as data. I think this is a mistake. Isn't it the retrieved json variable you want as data ?
"json_data" : {
"data" :json,
'data' : function (node) {
return { 'id' : node.id };
}

my ajax data is my pages html code?

Well i do a simple ajax request to my controller and when i console log it just shows the html from my webpage.
$(document).ready(function(){
$('.modelLink').click(function(){
var $reviewID = $(this).attr('data-id');
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
jQuery.ajax({
url: '/flyout',
type: 'post',
data:{
'reviewID':$reviewID
},
success: function( data ){
alert('Success Alert');
console.log(data);
}
});
});
});
Controller:
public function flyout(){
$result[] = ['value' =>'test', 'id' => '1'];
return Response::json($result);
}
Route::
Route::post('flyout','DashboardController#flyout');
So i get the pop up "success alert". but my console shows
<html>
<head>
<meta name="_token" content="UEUPcy9i7HMxTo65Ga2HumCplY158H8Ph5cD3eOP"/>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
and this carries on and matches my pages html content.
Why is this?

Knockout JS Script works in Chrome but not in IE9

I have a web page that works great in Chrome but not in IE9. The error that comes on the console from this error is
SCRIPT5022: Unable to parse bindings.
Message: [object Error];
Bindings value: foreach: statlist.
HTML is below:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="statsarea" data-bind="foreach: statlist">
<p> TypeCount: <strong data-bind="text: TypeCount"></strong>, Priority: <strong data-bind="text: SentDate"></strong>
<br/>
</p>
</div>
<script src="js/jquery-1.9.0.js" type="text/javascript"></script>
<script src="js/knockout-2.2.1.js" type="text/javascript"></script>
<script src="models/messagecount.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function MessageCountDataModel() {
var self = this;
var allCounts = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist = data;
}
});
})();
}
ko.applyBindings(new MessageCountDataModel());
One more piece of info is that that the json that comes out of the API looks something like this. I'm not sure if it's because the TypeCount is not a string?
[
{
"TypeCount": 102,
"SentDate": "2014-08-18T00:00:00.000Z"
}
]
It's not a good idea to use async: false. Maybe this is the problem because you don't initialize statlist as attribute in yout ViewModel. Better solution will be to make statlist to be an observable array, then make a async call and when it is ready to set the data.
Example:
function MessageCountDataModel() {
var self = this;
self.statlist = ko.observableArray();
self.loadData = function() {
$.ajax({
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist(data);
}
});
};
self.loadData();
}
ko.applyBindings(new MessageCountDataModel());

Categories