Http Json Post Response js - javascript

I have written a demo app at eclipse and I have a MySQL database.
I'm using hibernate to retrieve data from the database and now I want to
show up them to a browser.
I have a UserLogin class which is a servlet; the class waits for a HttpRequest and then the hibernate is being enable to bring me back the result set of the database.
By far, it works well; I have check my server side component using Postman and I do get a response as expected from my class, UserLogin.
My challenge is that I'm not really familiar with front-end.
I have the example below, using JavaScript with HTML in order to make a HTTP request.
I have check from my chrome browser's console and got the response below:
{"response":"ok","FileSystem":"Internal","userID":1}
but I need to be able to manipulate it (the response above) so as to display it on the page.
How can I achieve that?
<!DOCTYPE html>
<html>
<head>
<title>UserLogin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<p><input id="username" type="text" name="username" placeholder="username"></p>
<p><input id="password" type="password" name="password" placeholder="password"></p>
<button onclick="return login()">Submit</button>
<script>
function login() {
const params = {
username: document.querySelector('#username').value,
password: document.querySelector('#password').value
}
const http = new XMLHttpRequest()
http.open('POST', 'http://127.0.0.1:8080/.../UserLogin', true)
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8;')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
console.log(http.responseText)
}
}
</script>
</div>
</body>
</html>

Related

How do I update a html element with response from Ajax JQuery

I have an java application running, with a REST #POST endpoint, which takes an SQL query, and returns the result in a csv format.
The endpoint works, I can get the correct results via Curl and Postman.
Now, I am trying to call this endpoint via javascript, and to update a HTML value with the response. But have no experience with js.
This is the code I am using:
<!DOCTYPE html>
<html>
<body>
<h1>Making A POST</h1>
<p id="demo">Change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function loadDoc() {
$.post("http://localhost:4567/query/sql/csv",
"SELECT * FROM testTable",
function(data,status){
document.getElementById("demo").innerHTML = $result;
});
}
</script>
</body>
</html>
It is successfully making the POST request, can see from the application console. But it is not changing the HTML element with the response:
<p id="demo">Change this text.</p>
As I see, you're using a var that is undefined: $result
I think you wanted to use data instead.
Like this: document.getElementById("demo").innerHTML = data;
Code works.
The issue was Chrome and Internet Explorer blocking the script.

Trouble getting data from Firebase database Node.js/JavaScript

Good morning everyone I'm having a little trouble with Firebase as a new user. In my previous question I asked how I could use my express server making API calls to pass that data retrieved into my firebase database and I was able to make it work! However, now I want to take that data from my database and use it to populate my DOM on the client side.
So we're clear this is how the work flow got my app goes:
Make an AJAX request from my client to my express app app.jssending a small data object {search: search} where the value for search is captured in a form on the client. (works)
Take that data object and make another AJAX request to the third party API, which returns another data object. (works)
Take that response object from the third party API and send that to my database. (works)
A script client-side pulls information from my database to populate the DOM. (not working)
Looking at the myriad of tutorials is tough and I'm following the guides I find exactly using some fine copy pasta, but I'm still stuck.
Here is the client side script firebaseData.js that I'm using to retrieve data from my database, I'm trying to get all the data at the endpoint [my database url]/user:
$(document).ready(function() {
// create object instance of my Firebase database
var myDBReference = new Firebase([my database url]);
console.log(myDBReference.child("user"))
});
And it returns this in the console client-side:
X {k: Ji, path: P, n: Ce, pc: false, then: undefined…}
And that's all I've been able to get so far. Below is my index.html where I link to firebase it's cdn and a bunch of other stuff I was just told to include in my project:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="top">
<h1>Just Trying to Make a Halo App</h1>
<form id="searchForm">
<input id="searchField" type="text"></input>
<input id="searchButton" type="submit" value="search"></input>
</form>
</div>
<div id="imageContainer">
<img id="emblem">
<img id="spartan">
</div>
<div id="dataContainer">
<h2></h2>
<p></p>
</div>
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "[my key value]",
authDomain: "[authDomain value]",
databaseURL: "[databaseURL value]",
storageBucket: "[storageBucket value",
};
firebase.initializeApp(config);
</script>
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="request.js"></script>
<script type="text/javascript" src="firebaseData.js"></script>
</body>
</html>
In actuality the var config object has all the correct information generated from the firebase console- I wish that's all I would need to fix this! Please let me know if you require any more information I'd be happy to provide it and thanks for taking the time to check out my question.
Happy Saturday!
myDBReference.child("user") is just the reference to where the data is stored. To actually retrieve the data you will need to work with .on() or .once(). I strongly recommend you to take some time reading firebase documentation for retrieving data.
firebase.database().ref().child("user").once('value', function(snapshot) {
if(snapshot.value()){
//logs everything that is under /user
console.log(snapshot.value());
}
});
Keep in mind that if you have many users under /root/user, after retrieving the whole branch you will need to iterate over them with:
snapshot.forEach(function(childSnap){
console.log(childSnap.val());
});
Update:
Since I see you are not working with any SPA framework such as Angular (with angularfire), if you want to display the data that you are retrieving from firebase you will need to work setting an element id and than call document.getElementById() inside your callback to manipulate it.
<p id="username"></p>
document.getElementById("username").value = snapshot.val();

client request for get http://localhost:3000/test.s

I am creating my website using MEAN stack. on server NodeJs is running which has a route /test and is connected to DB. on the cleint side in Angularjs my client.ejs template include a script like
which is used in the controller in the page body.Now if i click on some page which hit the route /test and Nodejs renders load client.ejs. i can see an error " 500 internal error" for Get request http://localhost:3000/test.js
Why? it is happening like this?
nodejs code:
app.post("/test",function(req,res))
{
/do some stuff with req
res.status(200);
res.render("public/hello");
}
hello.ejs:
<html>
<head>
<script scr="test.js"></script>
</head>
<body ng-app="my-app">
<div ng-controller="my-controller">
<form ng-submit="dosction()">
<input type=text>
<input type=submit>
</form>
</div>
</head>
<html>
test.js
angular.module("my-app",[]).controller("my-controller", function($scope){
dosaction=function()
{
//some stuff
}});

Integrating Javascript Libraries with Google App Engine

Just starting to learn web programming (taking class CS 253 on Udacity).
My question is how does integrating JS and google app engine work? I know this is may be a fundamental question about web programming, but I really need some guidance on how to understand this concept.
I am trying to incorporate the Twitch Javascript API into Google App Engine. Basically, I would like to have a small website where users can login via Twitch and it stores their info into a database. I really do not understand how this is possible, since Twitch only has a Javascript API.
Here is the script that I have that works perfectly for connecting to Twitch (from the examples on their git page):
<html>
<head>
<meta charset="utf-8">
<title>TwitchTV SDK Example App</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ttv-api.s3.amazonaws.com/twitch.min.js"></script>
<script>
window.CLIENT_ID = '';
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.status input').val('Logged in! Allowed scope: ' + status.scope);
// Show the data for logged-in users
$('.authenticated').removeClass('hidden');
} else {
$('.status input').val('Not Logged in! Better connect with Twitch!');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read']
});
})
$('#logout button').click(function() {
Twitch.logout();
// Reload page and reset url hash. You shouldn't
// need to do this.
window.location = window.location.pathname
})
$('#get-name button').click(function() {
Twitch.api({method: 'user'}, function(error, user) {
$('#get-name input').val(user.display_name);
});
})
$('#get-stream-key button').click(function() {
Twitch.api({method: 'channel'}, function(error, channel) {
$('#get-stream-key input').val(channel.stream_key);
});
})
});
</script>
<style type="text/css">
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>TwitchTV SDK Example App</h1>
<div class="status">
Status: <input readonly="readonly" size="60" val="Unknown"/>
</div>
<div class="authenticate hidden">
<img src="http://ttv-api.s3.amazonaws.com/assets/connect_dark.png" class="twitch-connect" href="#" />
</div>
<h2 class="authenticated hidden">Authenticated</h2>
<div class="authenticated hidden">
<div id="logout">
<button>Log Out</button>
</div>
<div id="get-name">
<button>Get TwitchTV Name</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
<div id="get-stream-key">
<button>Get TwitchTV Stream Key</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
</div>
</body>
</html>
How can I communicate data between this client side javascript and Google App Engine? Thanks!
Very broad question. But in general, regarding your case:
You should set up a receiving end (handler) on your App Engine application. It will handle the requests from your client side JavaScript (Hello, world example)
Second, you will need to actually send the data to the server. I see that you're using jQuery. In order to call the server we've seen in the Hello, world example, you'll write something like this: $.get('/', function(data) {console.log(data);}). This will call the server and print to the console the message you got from the server.

How do I get a SignalR hub connection to work cross-domain?

I am trying to get a super simple hub connection working cross-domain but having no luck. I've read dozens of posts and done everything mentioned but still no success.
My server hub is here
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
My server MapHubs call is here
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
Any my javascript client is here
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.0.1.min.js"></script>
<script src="~/Scripts/jquery.signalR-1.1.2.min.js"></script>
<script src="/signalr/hubs"></script>
</head>
<body>
<div class="container">
<input type="text" id="displayname" value="Test" />
<input type="text" id="message" value="I'm here" />
<input type="button" id="sendmessage" value="Send" />
</div>
<script type="text/javascript">
$(function ()
{
$.connection.hub.url = 'http://<my url>/';
var chat = $.connection.chatHub;
alert(chat);
$.connection.hub.start().done(function ()
{
alert("Connection succeeded");
}).fail(function ()
{
alert("Connection failed");
});
});
</script>
</body>
</html>
The problem is that it never reaches the Connection succeeded or failed alerts and the alert(chat) call returns undefined.
I've tried several combinations for the $.connection.hub.url line
$.connection.hub.url = 'http://<My url>';
$.connection.hub.url = 'http://<My url>/';
$.connection.hub.url = 'http://<My url>/signalr';
$.connection.hub.url = 'http://<My url>/signalr/';
The developer console in Chrome and Firebug give me the error
Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/hubs'></script>.
On the same domain it works fine. This is really starting to drive me crazy so any help would be appreciated.
Thanks,
Jason
Your server is being hosted cross domain yet you're trying to get the hubs from the current domain. Therefore it's failing to retrieve the hubs file and you don't actually have a proxy to work with (which is why everything is not working).
So you have two options:
Manually create the hubs file and host it on the current domain: http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#manualproxy.
Use the raw hub connection API and do not include the signalr/hubs file at all.
Here's a code snippet of how you can use the raw hub connection API: http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#nogenconnection (second code snippet).

Categories

Resources