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

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

Related

How to change the value when I type ?variable=value at url?

Situation:
The input value is empty and the type is hidden.
I type ?hiddenname=007 at url
I click the button"submit" and cause function call()..
Expect:
The system fills in the value into the input according to ?hiddenname=007 at url using function call()
after that, the system send the form with value 007 to the server.
Current result:
the system still send the form with empty value.
url
localhost/index.html?hiddenname=007
index.html
<!DOCTYPE html>
<html>
<head>
<script>
function call(){
document.forms["form1"].hiddenname.value=hiddenname;
console.log("function run");
}
</script>
</head>
<body>
<form name="form1" action="end.php">
<input type="hidden" id="hiddenid" name="hiddenname" value="" />
<input type="submit" id="send" onclick="call()"/>
</form>
</body>
end.php
<?php
echo $_GET['hiddenname'];
?>
This will obtain on window load the value of hiddenname from the URL query string, then set the value of the hiddenid input:
window.onload = function () {
// get the search params from the window's URL
const urlParams = new URLSearchParams(window.location.search);
// get the value of 'hiddenname'
const myParam = urlParams.get('hiddenname');
// store this value in the input with id="hiddenid"
document.getElementById('hiddenid').value = myParam;
};
Add return true; to the call() function.
Add onsubmit="return call();" to the form attributes.
And remove onclick function from the submit button.

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 to make nusoap server with nusoap lib, and call using Javascript

I make nusoap server.php file with nusoap-0.9.5 php in my localhost,
now in index.html file, how can I call "getmessage" function using the javascript, such as:
Below code not working.. please help..
<?php //---server.php--begin---(php)
require_once("lib/nusoap.php"); //liberary
$server = new nusoap_server();
$server->configureWSDL("myService","urn:service1"); // configuare WSDL
function getmessage($message){
return "Welcome ".$message;
}
$server->register(
"getmessage",
array("name"=>"xsd:string"), //input
array("sum"=>"xsd:string") //output
);
//http listener
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA: '';
$server->service($HTTP_RAW_POST_DATA);
//---server.php--end---
?>
-------------------Javascript SOAP Client--------------------
<!---index.html--begin---(javascript html)--->
<SCRIPT language='javascript' src='soapclient.js'></SCRIPT>
<SCRIPT>
var url = "http://localhost/server.php?wsdl";
function getmessage()
{
var pl = new SOAPClientParameters();
pl.add("name", document.frmDemo.txtName.value);
SOAPClient.invoke(url, "getmessage", pl, true, getmessage_callBack);
}
function getmessage_callBack(r)
{
alert(r);
}
</SCRIPT>
<form id="frmDemo" name="frmDemo" action="" method="post">
<input name="txtName" id="txtName" value="Matteo" type="text">
<input type="button" value="click here" name="button" onClick="getmessage();"> <br>
</form>
<!---index.html--end--->
Javascript don't have stable library for soap, you must make it or use customized simple lib by any developers.. for example go to this link and do it:
https://www.ibm.com/developerworks/library/ws-wsajax/

POST JSON to Jersey Service

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.

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources