Can't submit JSON object to JSP - java

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.

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.

Post form without name preferably with JSoup

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.

i want to change value of a submit type button?

i have code of a form.
Code for submit button:
<input type="submit" id="submit" value="Save" />
After successfully saved this form, i want to change value of button to "Update".
I am using following code but it is not working.
$("#submit").click(function(){
$("#submit").val("Update");
});
More than likely, when you press the submit button, you are leaving the page and then reloading it.
You need to prevent the default behavior of the form and use AJAX to save the form.
Let say form is your form. You would do the following:
form.submit(function (e) {
e.preventDefault();
// ...and then your AJAX call.
// I won't go into the mechanics of AJAX,
// as there is lots of documentation online.
// Since you're using jQuery, I recommend http://api.jquery.com/jQuery.ajax/.
// Then, in your success function I would use your code:
$.ajax({
success: function () {
$("#submit").val("Update");
}
});
});
$("#submit").click(function(){
$("#submit").val("Update");
});
In this code the #Submit should be unique in the DOM. There shouldn't be any other element in the DOM with id submit. If there exists such an element the code will show irregularity.
I suspect that there may be more than one id=submit. try below code.
<input type="submit" id="submitButtonOne" value="Save" />
$("#submitButtonOne").click(function(){
$("#submitButtonOne").val("Update");
});
EDIT:
If your button is rendering dynamically try this
$(document).ready(function(){
$('body').on('click','#submitButtonOne',function(){
$(this).val("Update");
})
});
make sure that you have loaded jquery library.
try this
$(function(){
$("#submit").click(function(){
$(this).val("Update");
return false;
});
});

How to send values of the select box to servlet using ajax or jquery?

Im new to ajax. I want to redirect to servlet with the parameter value of the select box to my servlet. This is my code and its not retrieving values when I use request.getParameter("type") it gives me a null.
<script>
$(document).ready(function() {
$('#type').change(function() {
$.get('pickasset', function(responseJson) {
var type = $('#type').val();
$.ajax({
type:'POST',
url: 'PickAssetServlet',
data: type
});
});
});
});
</script>
<form action="pickasset" method="post">
<select id="type" name="type">
<option value="Non-Sap">Non Sap</option>
<option value="Sap">Sap</option>
</select>
</form>
When i change the select box, it must go to servlet and do logic there.
send your data like this-
data: { type : type }
If you're not getting the selected option from the select field, you need to use
$('#type').find(":selected").text() to retrieve the selected option. val() doesn't work with select fields. Also do what pXL said because that's how you send data with jQuery ajax methods
Check box value must be obtained from checkbox in the right way, as mentioned in jQuery docs (http://api.jquery.com/val/), just pay attention to multiple select, you're gonna have an array of values. You are doing it right, according to docs.
var varValue = var type = $('#type').val();
Then sending data as 'json' you will be able to read them with request.getParameter('type')
data: { "type" : varValue }
If you still get null, try to check if your "type" param and his value are in the request (chrome request inspector will be usefull, then check it in the debugger).
.
P.S.
Just check if you have something in your webapp filterchain that may wrap you request or hide some params, in some large web-app you get lost very easly.

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>

Categories

Resources