POST JSON to Jersey Service - javascript

I am trying to post some json data to REST web service implemented with Jersey framework. I am not using JAXB or jquery but only javascript.
I verified that formed json is correct but in spite of setting content type "application/json", on server it is received as "application/x-www-form-urlencoded".
Here is my code:
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = {};
var elem = document.getElementById('frmMain').elements;
//alert(elem.length);
for(var i = 0; i < elem.length-1; i++)
{
str[elem[i].name] = elem[i].value;
}
document.getElementById('lblValues').innerHTML = str;
var json = JSON.stringify(str);
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(document.getElementById('frmMain').method,
document.getElementById('frmMain').action);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-Length",json.length);
xhr.setRequestHeader('Accept', 'application/json');
//alert(json);
// send the collected data as JSON
xhr.send(json);
xhr.onloadend = function() {
// done
}
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" action="/JerseyTest/rest/postUser"
method="post">
<input name="firstName" value="harry" /> <input name="lastName"
value="tester" /> <input name="toEmail" value="testtest#test.com" />
<br /> <input type="submit" value="Test"
onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
On the server side:
package com.example.jersey.test;
import javax.ws.rs.*;
#Path("/postUser")
public class JsonTest {
#POST
#Consumes("application/json")
#Produces(MediaType.TEXT_PLAIN)
public String pingPong(String json) {
return "Answer is "+ json;
}
}
I am new to web development and not sure on what I am missing in above code.

I am answering my own question for those who may visit this later. The code above is correct and works well except the fact that the url is been hit twice. First time, for submit button's default action and then as per our script by XMLHttpRequest.
This I came to know after I checked the headers in Httpfox which showed error as NS_BINDING_ABORTED.
After changing the input type to button from submit, all is working fine.

Related

How to send Basic HTML Form data to Spring Boot controller?

How to send HTML Form request i.e; value of 'input' to #PostMapping in controller without creating any POJO class or jsp?
<body>
<form method="post" id="form">
<input type ="text"/>
</form>
<button type="button" id="button2" >Submit2</button>
<script src="script2.js"></script>
</body>
Script2.js
var select = document.getElementById('form');
document.getElementById("button2").onclick = function(){
var value = select.value
window.location.href = "/posting";
};
MyController.java
#PostMapping(value="/posting")
public String po() {
return "hello";
}
Specify the name for your input element:
<body>
<form method="post" id="form">
<input type ="text" name="someName"/>
</form>
<button type="button" id="button2" >Submit2</button>
<script src="script2.js"></script>
</body>
In your script create HTTPRequest and send data:
var select = document.getElementById('form');
document.getElementById("button2").onclick = function(){
var data = new FormData(select);
var req = new XMLHttpRequest();
req.open("POST", "/posting");
req.send(data);
};
You may also want to send JSON data. Convert data to JSON and send json variable
var object = {};
data.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
req.send(json);
And in java controller you have to specify that the method parameter is a request body. Something like this:
#PostMapping("/posting")
public String po(#RequestBody String someName) {
return "hello" + someName;
}
Check if controller class has #RequestMapping("/") annotation
you can use #RequestParam see RequestParam in Spring
add action attribute to form and make button in form (not needed js file because send direct by form):
<body>
<form action="/posting" method="post" id="form">
<input type ="text" name="someName"/>
<button type="submit" id="button2" >Submit2</button>
</form>
</body>
and change in controller :
#PostMapping("/posting")
public String po(#RequestParam("someName") String someName) {
return "hello" + someName;
}
but if need use js file you can use XMLHttpRequest see XMLHttpRequest api or ajax see jQuery.ajax or fetch fetch api

How to send AJAX Requests in custom form control (Alfresco Share)

I'm trying to develop an 'autocomplete' feature on element which will get data from the remote database (using simple HTTP GET requests which will return JSON).
In the workflow form, in share-conifg-custom.xml i provided control template:
<control template="/com/test/mytest.ftl"/>
And this is mytest.ftl:
<input type="text" name="search" id="search" placeholder="Type Something" list="searchresults" autocomplete="off">
<datalist id="searchresults"></datalist>
<script type="text/javascript">
myHttp = new XMLHttpRequest();
url='https://jsonplaceholder.typicode.com/posts';
myHttp.open("GET", url);
myHttp.send();
myHttp.onreadystatechange = (e) => {
var arr = JSON.parse(myHttp.responseText);
for (var i =0; i < arr.length; i++) {
var option = document.createElement("OPTION");
option.setAttribute("value", arr[i]["title"]);
document.getElementById("searchresults").appendChild(option);
}
}
</script>
The problem is that it does not send any requests.
What am I missing here?
As far as I understand, Freemarker template should convert it to HTML code and <script> tag should be executed on my browser.

Trying to Call a REST Web Service API from an HTML page in another project and GET an item's properties

I have one project that holds my REST web service API and another project that serves at my front-end. I want to enter a unique ID in an html text box and use that ID when calling the API to retrieve that ID's properties. I'm trying to use JavaScript to make the call to the Route that I have for the API call, but no luck.
My API controller has the call I'm trying to make:
<Route("orders/{id}/contents")>
<HttpGet>
Public Function GetOrderContents(ByVal id As String) As SPFolderOver
Dim retValue As ReturnVal
retValue = GetOrderInformation(id)
Dim ex = New Sharepoint()
Dim t = ex.GetOrderContent(retValue.Year, retValue.SONumber)
Dim myT = New SPFolderOver()
myT = SPFolderOver.LoadFolder(t)
myT.FolderName = t.Name
Return myT
End Function
My HTML with my JavaScript Function:
<head>
<script type="text/javascript">
function getContents() {
var on = document.getElementById("orderNumber").value
$.get(window.location.href = "http://localhost:54754/orders/{id}/contents"), $.get("orders/{id}/contents"), $("{id}").replaceWith(on);
}
</script>
</head>
<body>
<form id="eDocForm">
<div>
<input type="text" id="orderNumber" />
<input id="submitOrder" onclick="getContents()" type="submit" title="Submit" />
</div>
</form>
</body>
Your $.get does not look right. Try something like this:
$.get( "http://localhost:54754/orders/" + on + "/contents",
function( data ) {
// do something here with the returned data...
// alert( data );
});
You probably did not intent to submit the form, so change from:
<input id="submitOrder" onclick="getContents()" type="submit" title="Submit" />
to something like:
<input id="submitOrder" onclick="getContents()" type="button" title="Submit" />
I did not review your server side code as the functions, etc. are not fully defined there.

How do I call a python function from a cgi script with javascript?

I also want to use the XMLHttpRequest object in a javascript function to send info about the currently selected option from a dropdown list (the one called 'Users' in the code below) as an argument to a function in my Python script, and then get the return value from that function and use it to setup another list ('Tasks' in the code below) I want to do this so that I can update the information in "Tasks" using data that I have gotten as a return value from the Python function I am doing it this way because I need the page to not have to reload. If you know a better way to implement this I would be open to ideas.
def main():
with open("Users.json", 'r') as data_file:
usersDictionary = json.load(data_file)
Users=usersDictionary["Users"]
print "Content-Type: text/html"
print ""
print """
<html>
<head>
<script>
function setTaskList(){
#Insert Javascript which will call python function here...
}
</script>
<title>TestPage</title>
</head>
<body onload="setTaskList()">
<form>"""
print """<select name="Users" onchange="setTaskList()">"""
for user in Users:
if(not(len(user["Tasks"]["High"])==0 and len(user["Tasks"]["Med"])==0 and len(user["Tasks"]["Low"])==0)):
print """<option value="{0}">{1}</option>""".format(user["UID"], user["name"])
print "</select>"
print """<select name="Tasks" disabled="disabled">"""
print "</select>"
print"""<input type="Submit" value="Add Task"/>
<button type="button">Delete Task</button>"""
print"""
</form>
</body>
</html>"""
main()
For the code below, I want to be able to get the data from input boxes when submit is clicked, and send the info gotten from the input boxes and radio buttons to a python function to process it and add it as a JSON object to a JSON dictionary and then update a JSON file, and then return to the previous page (which is the one with the code above) (assume that is called index.py).
print "Content-Type: text/html"
print ""
print"""<html>
<head>
<title>Title</title>
</head>
<body>
<form action = "/~theUser/cgi-bin/index.cgi" method = "POST">
Task Name: <input type = "text" name = "TaskName"
placeholder="Task name" /> <br />
Task Description: <input type = "text" name = "TaskDescription"
placeholder="task description" /> <br />
User ID: <input type = "text" name = "UID" placeholder="User Id"
/> <br />
Priority <br/>
<input type="radio" name="gender" value="High"> High<br>
<input type="radio" name="gender" value="Medium"> Medium<br>
<input type="radio" name="gender" value="Low"> Low<br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>"""
Can anyone help, I'm really new to this CGI stuff, and would really appreciate it. Also if you know a better for me to do this, please let me know.
Thanks!
So after long trial and error, and waiting on an answer that never came, I figured out how to do this myself so I thought I might help whoever was in need of this out I was able to send a request from my python cgi script using javascript like so:
print "Content-Type: text/html"
print ""
print """
<html>
<head>
<script>
function getTasks() {
//put more processing in the function as needed
var xmlhttp;
var parameters = "This must be a string which will be the parameters
you will receive in your python script";
var scriptName = "pythonScript To CommunicateWith.py";
//may be .cgi as well depending on how you are using it
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", scriptName, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//retrieve a json response and parse it into userTasks
usersTasks = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.send(parameters);
}
</script>
In my python script which the java script hits here is how I get the arguments and process them:
#!usr/bin/python
import sys
import json
args=sys.stdin.readlines() #args comes in as a list with one item in it
which is the parameter that you sent in from javascript
arguments=args[0]
print "Content-Type: text/html"
print ""
def getTasks(userName):
"""This function will do some processing and get the required return
value"""
taskList=[]
#read JSON file and get the info.
with open("Somefile.json", 'r') as data_file:
usersDictionary = json.load(data_file)
data_file.close()
"""...do some process ing of data here, which will set some data into
the list called taskList"""
return taskList #Return a list of all the tasks for the user.
print json.dumps(getTasks(arguments))
"""convert the json to a string and print it out. what you print out here
will be what you will get as a string in the .responseText of the
XMLHttpRequest
object"""
Using Pycharm and the python CGIHTTPServer function to debug helped me here.
Hope this helps someone out there.

Loading .txt file into textarea Javascript?

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});

Categories

Resources