Post form without name preferably with JSoup - java

I am building an Android app and I want to post a html form that looks like this:
<form onsubmit="ShoutBox.postShout(); $('shout_data').value = ''; return false;">
Shout: <input type="text" id="shout_data" size="50"> -
<input type="submit" value="Shout Now!" id="shouting-status"></form>
I am using Jsoup in the rest of the application and I would preferably use it for this aswell.
I know about the .data(name, value) method, but since the html text and button don't have name attributes, that's not working. I can extract the field by using the ids and fill the field with: Element.val(String val); But I don't know how to post the form after that. Can anyone help me?
This is the JavaScript code for posting it:
postShout: function() {
message = $("shout_data").value;
if (message == "") {
return false;
}
$("shouting-status").value = ShoutBox.lang[0];
postData = "shout_data="+encodeURIComponent(message).replace(/\+/g, "%2B");
new Ajax.Request('xmlhttp.php?action=add_shout', {method: 'post', postBody: postData, onComplete: function(request) { ShoutBox.postedShout(request); }});
},

The post is not done via a form submit and post variables but via JavaScript and an XML HTTP request. JSoup is incapable to execute JavaScript. You need a browser that you can remote control. To do this headless in Java HTMLUnit is a good choice.

Related

React REST request to Java backend failing

I have a simple React form. I am trying to send the data from this form using Fetch API to my Java backend. Here is my React Form file:
import React, {Component} from 'react';
class Form extends Component {
constructor(props){
super(props);
this.state={value:""};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event){
event.preventDefault();
this.setState({value:event.target.value});
}
handleSubmit(event){
event.preventDefault();
const data = new FormData(event.target);
fetch('http://localhost:8080/add/person', {
method: 'POST',
body: data
});
}
render(){
return(
<form onSubmit={this.handleSubmit}>
<label>Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit"/>
</form>
);
}
}
For some reason, the data variable always has an empty JSON when I am in debug mode. In my Java backend, when I receive the request, I am seeing blank form data.
Any ideas as to why I am not able to send data across to my Java backend?
EDIT: I would also like to point out that my frontend is hosted on localhost:3000, while my Java backend server is on localhost:8080
why not just submit your data using the value stored in state?
handleSubmit(event){
event.preventDefault();
const data = this.state.value; //change here
fetch('http://localhost:8080/add/person', {
method: 'POST',
body: data
});
}
UPDATE: in your package.json add "proxy": "http://localhost:8080" if that doesn't work you will have to open it up using something like this but for what ever framework you're using on your backend.
https://www.npmjs.com/package/cors#enabling-cors-pre-flight
http://www.baeldung.com/spring-cors
as #Tadas Antanavicius said your input is also missing a name value. here is a nice and short medium article on the react portion of what you are trying to do with your code. you can even remove your onChange from your input field.
https://medium.com/#everdimension/how-to-handle-forms-with-just-react-ac066c48bd4f
Your problem is unrelated to your backend - the fetch code looks correct.
FormData is not being constructed as you would expect. You can try this out by opening Chrome Devtools' Network tab and watch the request as it goes by: empty request payload.
The problem is that the FormData constructor's argument relies on each input in the form having a name attribute, which you're missing. If you add it, (name="name") your front end should behave as expected:
<input type="text" name="name" value={this.state.value} onChange={this.handleChange} />
EDIT: As per your above conversation, seems like you also have a server side CORS issue. My answer fixes your original question, but yes you'll need to resolve the CORS one as well, the easiest way probably being to refer to the docs of whatever Java framework you're using. It's a very common problem and should be in FAQ.

Can't submit JSON object to JSP

I'm trying to send a JSON object to a JSP to parse. The JavaScript code is:
function sendData(field1, oper1, value1, field2, oper2, value2, field3, oper3, value3){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}, function(response){alertHere(response)});
}
function alertHere(){
window.alert("Post Successful!")
}
My submit button is:
<input type="submit" value="SEARCH" name="submit" class="srchbutton" onclick="sendData(document.getElementById('field1').value, document.getElementById('oper1').value>
There are several more fields passed in the JavaScript button on click, I just didn't want to post that long of a line.
When I try to post with text data in the form, my web developer console flashes the path to my JSP really quickly then disappears. It's too fast to see the error. If there's no data, the post is successful, as my alertHere function in $.post() is called correctly. I'm not sure if I'm missing something.
Assuming you have a servlet on the server side which handles the data you are sending from the jsp page you could create a pseudo-class using javascript, then parses it to json and finally sends it to the server. for example:
javascript and jQuery
function SomeClass (){
this.field1 = $("#field1").val();
this.oper1 = $("#oper1").val();
this.value1 = $("#value1").val();
// etc. for every field you want to send
}
note: i'm assuming every field have an id.
function alertHere(){
window.alert("Post Successful!")
}
jQuery and ajax
$("#someID").click(function(){
event.preventDefault(); <-------- if you replace the submit button for a simple button,
you don't need to do this.
var formData = new SomeClass();
$.ajax({
url:"ServletName",
data: JSON.stringify(formData),
dataType:"json",
}).done(function(response){
alertHere(response);
});
});
html
<input type="submit" value="SEARCH" id="someID" name="submit" class="srchbutton">
Try changing this line of code
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}
To
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:Json.stringify(formData)}
Not entirely sure if this would work, Just a suggestion.
Figured it out. The problem was that I wasn't passing my "response" to my success function, so:
function alertHere(){
window.alert("Post Successful!")
}
should have been:
function alertHere(response){
window.alert("Post Successful!")
}
It was probably posting correctly, but I wasn't getting a success because the response wasn't getting passed.

Ajax response in datatables

I was implementing an interface with uses DataTables and excel files. Motive is upload an excel and then show it in DataTables.
As I didn't find any javascript library which parse the excel and provide it to DataTables. The only option is ot send the data to the front end struts/ java and send back the json.
Is it possible to have DataTables waiting for the json by Ajax without sending the request. .
i think, it is possible in html5 and javascript. run and test the code below.
<html>
</head>
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop);
reader.readAsBinaryString(blob);
}
</script>
</head>
<body>
<input type="file" id="files" name="file" accept=".csv" />
<span class="readBytesButtons">
<button onclick="readBlob()">entire file</button>
</span>
<div id="byte_range"></div>
<div id="byte_content"></div>
</body>
</html>
we can extract the excel data as text by FileReader in javascript.
if you want to display the data in datatable, please apply your logic.
Yes off course,
I think you want to try something like this
upload file to server
read the excel file in strut action, save it on disk in temp folder and return file name to your JSP.
when first step done then make Ajax Call to struts action
pass file name as parameter fom datatable ajax call
load file from disk read it and populate in Pojo or VO object
create Json from Pojo using gosn or jakson api
finally return json.
further see data table ajax source
Yes this is possible, but no Ajax is need in your case. How would i do it? See below:
Have a form to upload the excel file to my struts implementation. Then do the processing of the excel file and return the contents in pure html/table format. Then do a simple datatables initialization on page load and your are finished!
UPDATE
For pagination, datatables support ajax like this:
var oTable = "";
$(document).ready(function() {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "/myAjaxSource.jsp?page="+pageNumber+",
"sServerMethod": "POST",
"iDisplayLength": 50
});
}
Then in your myAjaxSource.jsp you get the parameter page sent by the ajax URL and return the appropriate data (json)

How to create Autocomplete textbox from database results in a html page using java servlet, jquery, json object by making an ajax call

I have tried different things but i am not able to do this.
I am very new to jquery json and ajax. I wrote a servlet which connects to my databse and retrive user ids from the table. I wrote a jsp and which has a text box that takes input text and refines the results on each key press I want to do it in a html page using jquery ajax by sending json object from my servlet. can someone give me an example for this scenario.
Thanks in advance.
http://jsfiddle.net/tAjNz/
<input type="text" />
<select id="autoPop" multiselect="true"></select>
<script>
// define a data source (ajax or on page load);
myJson = [{value:1,text:'Item One'},{value:1,text:'Item Two'},{value:1,text:'Item Three'},{value:1,text:'Item Four'}];
$('input[type="text"]').keyup(function(){
//Optionally update the data source when a user starts typing or use the predefined source.
//Populate the select list
$sel = $('select');
$sel.html('');
var $this = $(this);
$.each(myJson,function(k,v){
if(v.text.toLowerCase().indexOf($this.val().toLowerCase()) > -1) {
$sel.append('<option value="' + v.value+ '">'+ v.text+'</option>');
}
});
});
</script>

calling a java servlet from javascript [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 1 year ago.
I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.
Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.
Can anybody help me out?
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World! in the JavaScript alert.
You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
The code here will use AJAX to print text to an HTML5 document dynamically
(Ajax code is similar to book Internet & WWW (Deitel)):
Javascript code:
var asyncRequest;
function start(){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open('GET', '/Test', true); // /Test is url to Servlet!
asyncRequest.send(null);
}
catch(exception)
{
alert("Request failed");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
{
var text = document.getElementById("text"); // text is an id of a
text.innerHTML = asyncRequest.responseText; // div in HTML document
}
}
window.addEventListener("load", start(), false);
Servlet java code:
public class Test extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException{
resp.setContentType("text/plain");
resp.getWriter().println("Servlet wrote this! (Test.java)");
}
}
HTML document
<div id = "text"></div>
EDIT
I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):
document.location = 'path/to/servlet';
Where your servlet-mapping in web.xml looks something like this:
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

Categories

Resources