Function to get IP Address in an Ajax Get Method - javascript

I'm new to Programming and have this assignment of using JQUERY Ajax method in Javascript to get the data of a Gateway and attach some of it's value to the properties of an object. That I have already done but in the object is an "ip" property and it's value should be the ip in the url in the get request. I have over this for for hours and can't figure it out but i believe there's a simple way to go about it. Below is code and i hope someone out there can help out.
<!DOCTYPE html>
<html>
<head>
<title>Gateway Object</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script src="jquery-2.1.4.js"></script>
<script>
gateway = {
ip: "",
hwv: "",
ver: "",
sid: ""
};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://192.168.55.146/command?XC_FNC=GetSI",
timeout: 2000,
error: function (err) {
console.log("gateway error: check ip address and try
again");
},
success: function (data) {
if(data) {
if(data.substr(0,8) === "{XC_SUC}") {
var jString = (data.slice(8));
var obj;
try {
var obj = JSON.parse(jString);
} catch(e){}
gateway.hwv = obj.HWV;
gateway.ver = obj.VER;
gateway.sid = obj.SID;
console.log(gateway);
}
else{
console.log("Error:" + "" + data);
}
}
else{
console.log("error with the gateway");
}
}
});
});
</script>
</head>
<body></body>
</html>

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

Chaining function with then doesn't work correctly

Hey I got a problem which my functions which are chained with .then doesn't work correctly, not in the order they should.
my code:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
var users = [];
var user = null;
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET",
success: function(response) {
users = response.data;
console.log("users", users);
}
});
}
function restCallB() {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET",
success: function(response) {
user = response.data;
console.log("user", user);
}
});
}
function myFun(testArg) {
users.push(user);
console.log("why users is null?", testArg, users);
}
$(function() {
restCallA()
.then(restCallB)
.then(myFun("test"));
});
</script>
</body>
</html>
output:
users variable on the myFun function should have all the data from the first restCall and push the data from the second restCall to the same variable.
The variables does get the data, but the myFun function runs before them so the users variable inside it is null.
result pic:
how can I fix that?
.then accepts a function as a parameter, but in
restCallA()
.then(restCallB)
.then(myFun("test"));
you're invoking myFun immediately, and passing its return value to the second .then. It evaluates to:
restCallA()
.then(restCallB)
.then(undefined);
The myFun runs immediately, while the interpreter attempts to put together the Promise chain (before the response has come back).
Pass a function that invoked myFun instead:
restCallA()
.then(restCallB)
.then(() => myFun("test"));
You may also use .bind, which will create a function with the desired parameters, but won't call it:
restCallA()
.then(restCallB)
.then(myFun.bind(undefined, "test"));
var users = [];
var user = null;
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET",
success: function(response) {
users = response.data;
console.log("users", users);
}
});
}
function restCallB() {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET",
success: function(response) {
user = response.data;
console.log("user", user);
}
});
}
function myFun(testArg) {
users.push(user);
console.log("why users is null?", testArg, users);
}
$(function() {
restCallA()
.then(restCallB)
.then(() => myFun("test"));
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Only invoke a function inside a .then's parameter list if the function returns a function, eg:
const fnThatReturnsFn = arg => resolveValue => console.log(arg, resolveValue);
someProm()
.then(fnThatReturnsFn('somearg'));
$.ajax returns a promise-like object. so use that to your advantage, by returning the data from your ajax calls in a then within your functions.
Note that I've used one of #CertainPerformance's suggestions in their answer to fix the myFun issue.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET"
}).then(response => response.data);
}
function restCallB(users) {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET"
}).then(response => {
return {
// ES2015 method for adding a property named "users" with the value of the users variable
users,
user: response.data
};
});
}
function myFun(testArg, usersAndUser) {
usersAndUser.users.push(usersAndUser.user);
console.log(testArg);
}
$(function() {
restCallA()
.then(restCallB)
.then((usersAndUser) => myFun("test", usersAndUser));
});
</script>
</body>
</html>
Note that I'm using an object to collect both users and user into a single object; you could just as easily use an array.

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 };
}

How do I setup simple firebase ajax request?

I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. When I load test.html in my browser, the console says -
XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
//text.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Firebase Test</title>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
</head>
<body>
<div id="hi"></div>
<script src="https://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/json',
type: "POST",
data: param,
success: function () {
alert("success");
}
});
});
</script>
</body>
</html>
//firebase rules
{
"rules": {
".read": true,
".write": true
}
}
Firebase expects the body to be a JSON string, so you'll need to stringify it:
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/.json',
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("success");
},
error: function(error) {
alert("error: "+error);
}
});
});
This will accomplish the same by the way:
$.post('https://jleiphonebook.firebaseio.com/.json',
JSON.stringify(param),
function () {
alert("success");
}
);

ajax call passing security

I am trying to make an ajax call (using IE 10) to a page that returns json (not jsonp) but I keep getting a "401 - Unauthorized: Access is denied due to invalid credentials." The site is setup in IIS to use "Windows Authentication", however, if I change the site to enable Anonymous Authentication the call works. Below is the code I am using to make the call. What am I missing with my call or what do I need to change on my webserver? The Windows Authentication is currently set up to use NTLM authentication on the Windows Auth.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="scripts/jquery-2.0.3.min.js"></script>
<script src="scripts/base64.js"></script>
<script type="text/javascript">
function QueryMyData() {
var postUrl = 'http://mydevpage/storage.ashx';
var data = 'AssetNumber=102405';
$.support.cors = true;
$.ajax({
type: "POST",
url: postUrl,
data: data,
dataType: 'json',
crossDomain: true,
cache: false,
username: "mydomain.net\\myuser",
password: "password",
beforeSend: function (xhr) {
xhr.withCredentials = true;
},
success: function (result) {
if (result) {
if (result.error)
alert(result.error);
else
alert(result.id);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Unknow Error:' + thrownError + ajaxOptions + xhr.status + " " + xhr.statusText);
}
});
}
QueryMyData();
</script>
</head>
<body>
</body>
</html>
I found a solution to my problem. While I was not ever able to get the ajax request to work with security hitting a page on another domain, I did find a way to accomplish this. I ended up creating a ProxyHandler.ashx page and setting the permission on the request using the WebClient.
html page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function QueryMyData() {
var postUrl = './ProxyHandler.ashx?http://mydevpage/storage.ashx';
var data = 'AssetNumber=102405';
$.support.cors = true;
$.ajax({
type: "POST",
url: postUrl,
data: data,
dataType: 'json',
cache: false,
success: function (result) {
if (result) {
if (result.error)
alert(result.error);
else
alert(result.id);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Unknow Error:' + thrownError + ajaxOptions + xhr.status + " " + xhr.statusText);
}
});
}
QueryMyData();
</script>
</head>
<body>
</body>
</html>
Here is the proxy page (ProxyHandler.ashx)
public class ProxyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string username = "svcMyServiceAccount";
string password = "password";
try
{
string uri = context.Request.RawUrl.Substring(context.Request.RawUrl.IndexOf("?") + 1);
if (uri.StartsWith("ping"))
{
context.Response.Write("<html><body>Hello ProxyHandler</body></html>");
return;
}
context.Response.ContentType = "text/plain";
byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes, 0, (int)context.Request.InputStream.Length);
var data = System.Text.Encoding.UTF8.GetString(bytes);
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//this is the magic of getting auth passed. See post http://stackoverflow.com/questions/1680718/domain-credentials-for-a-webclient-class-dont-work
wc.Credentials = CreateCredientialCached(uri, username, password, "mydomain");
var response = wc.UploadString(new Uri(uri, UriKind.Absolute), "POST", data);
context.Response.Write(response); //already in the JSON Reponse class format
}
}
catch (Exception e)
{
context.Response.Write(GetJSON(string.Empty, e));
}
}
private CredentialCache CreateCredientialCached(string uri, string userName, string userPassword, string domain)
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(uri), "NTLM", new NetworkCredential(userName, userPassword, domain));
return cc;
}
private string GetJSON(string id, Exception error)
{
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new Response() { id = id, error = error != null ? error.ToString() : string.Empty });
return json;
}
// Necessary for IHttpHandler implementation
public bool IsReusable
{
get { return false; }
}
private class Response
{
public string id { get; set; }
public string error { get; set; }
};
}

Categories