getJSON - How to print out the result, and how to retrieve input? - javascript

I implemented some java functions. Now I have to present the result to the user via html.
public Object post()
{
responseHeaders.put("Content-Type", "application/json");
try
{
final User user = UC0_Login.getLoggedInUser(this);
List<Measurement> mylist = MeasurementService.getMeasurementsbyPatient(user.getUsername().toString());
for(int i = 0; i < mylist.size(); i++) {
Measurement mesPatient = mylist.get(i);
DownloaderService.saveTxt(mesPatient);
// System.out.println("Test Name: " + mesPatient.getRequest().getPatient().getFirst_name().toString());
}
}
catch(HttpException x)
{
x.printStackTrace();
this.statusCode = x.getStatusCode();
return "{ \"success\": false }";
}
catch(Exception x)
{
x.printStackTrace();
this.statusCode = StatusCode.SERVER_ERROR_500;
return "{ \"success\": false }";
}
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
String result = "Your measurements have been saved at" + tempDir;
return result;
}
There I implemented post(), in a Java class. I also created a HttpServer in the background. As shown in the code, I return a String. How can I print out that string in HTML? And how can I get input (for example an integer) from HTML into for example a get() function? Thank you!!!

If you are basically looking for AJAX request and response, here is a good source to learn how to.
https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting
For example,
HTML
<p id="result"></p>
<form id="frm1" action="/action_page.php">
Your input: <input type="text" id="myInput"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
JAVASCRIPT
var input = document.getElementById("myInput").value;
xhr = new XMLHttpRequest();
xhr.open('POST', 'Your URL Goes Here');
xhr.onload = function() {
if (xhr.status === 200) {
var response = xhr.responseText;
document.getElementById("result").innerHTML = response;
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI('input=' + input)); // Use your API param keys here

Related

How can I retrieve plane text data from one local ip to another in javascript?

I am using an ESP32 Wifi module as a master to host a webpage displaying the values of a number of binary data points in a table as either OK or FAILED. I need to have this device retrieve data from another ESP32 client on a local IP i.e 192.168.138.50/readVal1 this address will display simply plane text either OK or FAILED. I would like to take this value and display it in the table produced by my master module. How should I go about doing this?
I have tried using an HTTP get request as follows in the Arduino code.
void runTest6(){
String payload;
HTTPClient http;
http.begin("192.168.137.50/readBatt1");
int httpCode = http.GET();
if(httpCode > 0) {
payload = http.getString();
Serial.println(payload);
}else{
Serial.println("HTTP request error");
}
http.end();
String batt6val = payload;
server.send(200, "text/plane", batt6val);
}
Here is my Javascript on the root that handles the updates\
function getData(){
try{
console.log("Getting Data...");
for(var i = 1;i<=NUMOFUNITS;i++){
(function (i){
setTimeout(function () {
console.log("(debug msg)in loop #: " + i)
var xhttp = new XMLHttpRequest();
var current = "batt" + i + "val";
var dataRead = "readBatt" + i;
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
console.log("updating innerHTML for data value: " + i);
document.getElementById(current).innerHTML = this.responseText;
}else if(this.readyState == 4 && this.status == 404){
console.log("no battery # " + i);
document.getElementById(current).innerHTML = "None found";
}
};
xhttp.open("GET", dataRead, true);
xhttp.send();
if(i == 1){
updateTime();
console.log("Updated times.")
}
}, 400*i);
})(i);
};
console.log("Data update complete.");
}
catch(err){
alert(err.name);
throw err;
getData(); //try to get data again
}
finally{
console.log("DONE");
}
}
Using and HTTP server I am able to send the information between ESP32's. Using the WebServer I have set server.on("/status/{}", sendData); where the {} hold the pathArg aka a number representing which data is being asked for. The function senData() takes the pathArg and sends the appropriate data as follows.
void sendData(){
String battString = server.pathArg(0);
Serial.println("Sending Data... PathArg= " + battString);
int battNum = battString.toInt();
int arrayNum = battNum - 1;
server.send(200, "text/plane", battStatus[arrayNum]);
}
Here an array called battStatus holds the status of each.

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

Getting 406 Error in Ajax Response using Spring MVC

I am learning Ajax and trying to get it work on my project. Basically i am trying to implement google like suggestion on the project.
i have a UI that sends ajax request to the server asynchronously and gets relevant suggestion
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
console.log(str);
var xmlhttp = new XMLHttpRequest();
console.log(xmlhttp.readyState);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "/hint?word=" + str, true);
xmlhttp.send();
}
}
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)">
<p id="peak"></p>
<p>Suggestions: <span id="txtHint"></span></p>
The Spring MVC controller is
#RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public #ResponseBody ArrayList<String> hint(ModelMap model,#RequestParam String word) {
System.out.println("Inside Hint");
String[] hints = { "Ram", "Shyam" };
ArrayList<String> returnhint = new ArrayList<String>();
// lookup all hints from array if $q is different from ""
if (word != null) {
word = word.toLowerCase();
int length = returnhint.size();
for (int j = 0; j < length; j++) {
if (word.contains(hints[j])) {
returnhint.add(hints[j]);
}
}
}
return returnhint;
}
I am new to Ajax. So is there a specific way xmlhttp object's responseText have to be handled?
My question is since i have passed ArrayList in the response body, how do get ajax to get that response and update the UI accordingly?
To use #ResponseBody you need two things:
<mvc:annotation-driven /> in your context file
a library to handle JSon (like Faster Jackson) in your classpath
If you don't configure well the spring part you will have a 406 error because the header of the response is not correctly initialized and the response itself is not in the right format.
Going through the documentation, xmlhttprequest object has a set of properties to handle response
XMLHttpRequest.response Read only
Returns an ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, depending on the value of XMLHttpRequest.responseType. that contains the response entity body.
So i basically returned a String instead of a ArrayList and concatenated all of the matched hints in the string using comma ',' separator
And in the javascript file. I simply made a list of the reponse with split(',') function.
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
console.log(str);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var list=xmlhttp.responseText.split(',');
console.log(list);
document.getElementById("txtHint").innerHTML = list;
}
};
xmlhttp.open("GET", "/hint?word=" + str, true);
xmlhttp.send();
}
}
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)">
<p id="peak"></p>
<p>Suggestions: <span id="txtHint"></span></p>
Controller Method
#RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public #ResponseBody String hint(ModelMap model,#RequestParam String word) {
System.out.println("Inside Hint");
String[] hints = { "Ram", "Ra","R","Shyam" };
String returnedhints="";
// lookup all hints from array if $q is different from ""
if (word != null) {
System.out.println("i am here");
//word = word.toLowerCase();
int length = hints.length;
for (int j = 0; j < length; j++) {
System.out.println(word+"contains"+hints[j]+"="+word.contains(hints[j]));
if ((word.regionMatches(0, hints[j], 0, hints[j].length())) {
returnedhints= returnedhints+","+hints[j];
}
}
}
return returnedhints;
}
Hope this will be helpful to future ajax learner with spring mvc.

Upload Document to Web API

First Step: On my MVC project I have a Div that allow to upload a file.
<div id="modalUpload" style="display:none">
Select a file:
<input id="upload" type="file" name="upload" /><br />
Description:
<input id="documentDescription" type="text" /><br />
<input type="button" value="Submit" id="submitUpload" data-bind="click:function(){ $root.upload() }">
</div>
Second Step: In JavaScript I upload the Document to the web API with a POST request: (for example, with the XMLHttpRequest method)
self.upload = function () {
var file = document.getElementById("upload").files[0];
var xhr = new XMLHttpRequest();
xhr.open('post', "/API/document/addDocument/", true);
xhr.send(file);
}
Third Step: This is my addDocument function on the Web API that expects a Document object, like this:
[HttpPost]
[Route("{controller}/addDocument")]
public string Post([FromBody]Document doc)
{
.......
}
My question is, how can I post the Document to the API as a Document object? Is it possible to set the type of the POST data?
On my JavaScript code, I have a Document object:
var Document = function (data) {
this.id = ko.observable(data.id);
this.name= ko.observable(data.name);
this.size= ko.observable(data.zise);
}
But I'm not sure how to connect between them.
When I tried this:
var file = new Document(document.getElementById("upload").files[0]);
I got the following error:
415 (Unsupported Media Type)
Any help would be very much appreciated.
One possible issue is that you'll need to make sure your XHR request declares the correct MIME type in the accept header.
Using XHR directly can be a bit of a pain. You may want to consider using a client-side library (such as jquery) to make things easier and handle any cross-browser inconsistencies.
You could try getting it as an HttpPostedFileBase
[HttpPost]
[Route("{controller}/addDocument")]
public string Post(HttpPostedFileBase doc)
{
//Parse it to a doc and do what you gotta do
}
Finally, I didn't send the document as an object, and this is what I ended up doing,
self.upload = function () {
if (document.getElementById("upload").value != "") {
var file = document.getElementById("upload").files[0];
var filePath = "....";
if (window.FormData !== undefined) {
var data = new FormData();
data.append("file", file);
var encodedString = Base64.encode(filePath);
$.ajax({
type: "POST",
url: "/API/document/upload/" + file.name + "/" + encodedString ,
contentType: false,
processData: false,
data: data,
success: function (result) {
console.log(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
}
}
}
And this is my API function:
[HttpPost]
[Route("{controller}/upload/{fileName}/{filePath}")]
public async Task<HttpResponseMessage> UploadFile(string fileName, string filePath)
{
if (!Request.Content.IsMimeMultipartContent())
{
return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The request doesn't contain valid content!");
}
byte[] data = Convert.FromBase64String(filePath);
filePath = Encoding.UTF8.GetString(data);
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var dataStream = await file.ReadAsStreamAsync();
// use the data stream to persist the data to the server (file system etc)
using (var fileStream = File.Create(filePath + fileName))
{
dataStream.Seek(0, SeekOrigin.Begin);
dataStream.CopyTo(fileStream);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain");
response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(#"text/html");
return response;
}
return Request.CreateResponse(HttpStatusCode.ExpectationFailed);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
That works perfectly, I got the idea from here.

Categories

Resources