Submit list of objects from jsp to controller - javascript

I have dynamically varying list of parameters that I need to pass from a jsp page to spring mvc controller, how do I achieve this? Please provide a suggestion or a pseudo code so that I can proceed with my development.

Have you considered this:
<form id="myForm" action="blammo">
<input type="hidden" name="hoot"/> <!-- dynamically add hidden elements to -->
<!-- myForm then submit it -->
</form>

You can use ajax from the .jsp to your controller with POST or GET.
.jsp:
<%
Gson gson = new Gson();
%>
<script>
var json = "<% out.println(gson.toJson(myList).toString()); %>";
function sendData() {
"use strict";
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log("data send to my controller ...");
}
};
xhr.open("GET", "http://localhost:8080/url_of_my_controller?value=" + json, false);
xhr.send(null);
}
</script>
controller.java:
#RequestMapping(value = "/url_of_my_controller", method = RequestMethod.GET)
public #ResponseBody String controller(HttpServletRequest request, HttpServletResponse response) {
if (request.getParameter("value") != null) {
Gson gson = new Gson();
List<foo> list = gson.fromJson(request.getParameter("value"), List<foo>);
System.out.println(request.getParameter("value"));
return ("ok");
}
return ("ko");
}

Related

C# - Sending a XML over to Action result via JavaScript in cshtml

I have a .cshtml file which contains JavaScript function to perform a POST action to my controller class.
<input type="text" placeholder="Username" id="username" />
<button type="submit" onclick="sendResult()">Submit</button>
<script type="text/javascript">
function sendResult() {
let username = document.getElementById('username').value;
try {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test/Test");
xmlhttp.setRequestHeader('Content-Type', 'text/html');
let xml = `<?xml version="1.0"?><query><Username>${username}</Username></query>`;
console.log(xml)
xmlhttp.send(xml);
let xmlResponse;
xmlhttp.onreadystatechange = async function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
xmlResponse = await xmlhttp.responseXML;
console.log(xmlResponse)
}
}
} catch (error) {
console.log(error)
}
}
</script>
In my controller class, I did not manage to receive the xml string (myXML) after clicking on the submit button. Why is that so?
// TestController.cs
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(string myXML)
{
Service1Client o = new Service1Client();
o.Test(myXML);
return View();
}

how to add parameter into HttpContext.Request.Form from client side

I wanted to know how to add parameters into HttpContext.Request.Form via client side so that in the serve side i can get these data
i don't want to use ajax.
I tried the following but with no success:
javascript code:
var request = new XMLHttpRequest();
request.open("POST", window.location.host, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.append('skip', '10');
request.send(formData);
the asp.net mvc line of code:
var a = HttpContext.Request.Form.GetValues("skip");
but a is equal to null.
thank you all
Update:
I want to do something like datatable. In datatbles you can set draw,start, col_order etc. And you can get it with request into the server side. I want to know how can i do something like that.
You will need to combine data like this - "key1=value1&key2=value2&skip=10".
View
<button type="button" onclick="postData()">Post data</button>
<div id="result"></div>
<script>
function postData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("POST", "#Url.Action("PostData", "Home")", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2&skip=10");
}
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult PostData(FormCollection collection)
{
var key1 = collection["key1"];
var key2 = collection["key2"];
var skip = collection["skip"];
return Json($"key1: {key1}, key2: {key2}, skip: {skip}");
}
}
Screen Shots

Controller not receiving data?

i'm trying to send data from a view to a controller using POST but i doesn't seems to work.
Here's my code (javascript function) :
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
var titre = str;
xmlhttp.open("POST", "CheckReturn", true);
//xmlhttp.send(titre);
xmlhttp.send({"titre":titre});
}
}
the html triggering it :
<div id="check-name" class="form-row">
<input id="name" type="text" name="name" placeholder="Titre de l'événement" onkeyup="showHint(this.value)">
<span id="txtHint"></span>
</div>
and finally, the controller SUPPOSED to get it :
[HttpPost]
public ActionResult CheckReturn(string titre)
{
var contexte = new intranetEntities();
var ajax = contexte.evenementiel.SqlQuery("Somequery" + titre);
ViewBag.ajax = ajax;
return PartialView();
}
i checked bit firebug, the data is sent, but with visual studio's debugger, i see that "titre" always stay null.
What can i do ?
I've run into something similar in the past with asp.net but I never really tried to understand what's happening. What fixed it for me was the following:
make a new class somewhere in your back-end (anywhere, doesn't matter for now)
class TitreWrapper {
public string titre {get; set;}
}
then in your controller
[HttpPost]
public ActionResult CheckReturn(TitreWrapper titreWrap)
{
string titre = titreWrap.titre;
}
this should work according to my previous experience
the top answer is wrong (but right in other circumstances I think)
for this problem the following worked:
xmlhttp.open("POST", "/CheckReturn?titre=" + titre, true);
and then just
xmlhttp.send();
OR
xmlhttp.open("POST", "CheckReturn", true);
then
xmlhttp.send("titre=" + titre);

How to send a POST request to send BLOB data from client java script and receive it via MVC controller?

My current code:
Javascript
function pushFunc() {
mediaRecorder.requestData();
console.log(mediaRecorder.state);
mediaRecorder.ondataavailable = function (e) {
console.log("data size: ", e.data.size);
var encodeData = new Blob([e.data], { type: 'video/mp4' });
postBlobData(encodeData);
}
}
function postBlobData(blob) {
var formData = new FormData();
formData.append("blobContent", blob);
var request = new XMLHttpRequest();
request.open("POST", "/Device/Upload");
request.send(formData);
}
ASP.NET
**File: DeviceController.cs**
[HttpPost]
public string Upload(HttpPostedFileBase blobContent)
{
...
// return View();
}
The Java script code gets the blob from Media recorder and tries to post it down to the Controller.
Am i grabbing and posting blobs the way i should?
Should HttpPostedFileBase be used to receive the post request on the server side?
Fiddler Screenshot#1
Fiddler Screenshot#2
Fiddler Screenshot#3

not receiving data from http inputstream

function sendRequestToDelicious()
{
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
var url = "http://localhost:52271/WebForm1.aspx";
var params = "q=hello";
xmlhttp.open("POST", url, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);
}
In my ASP.NET app, I am reading the stream from page_load event, but I'm not receiving the data. what am I doing wrong?
C# CODE IN ASP.NET:
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(Page.Request.InputStream);
String data = reader.ReadToEnd();
}
...
It looks like this post contains the precise code for what you are trying to do:
Fake a form submission with C# WebClient
If you just need the data at Page_Load there isn't a requirement to do this with JavaScript- right?
I personally don't use the XmlHttpRequest object any more. I have abandoned it in favor of using the jQuery AJAX functions. The callback function for a successful post would make it easy to capture the response from the server.
Here is an example of how to do it with jQuery AJAX:
$.ajax(
{
type : 'POST',
url : 'http://localhost:52271/WebForm1.aspx',
dataType : 'json',
data:
{
q:'hello'
},
success : function(data)
{
$('mydiv').text(data.msg).show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
$('mydiv').text('There was an error.').show(500);
}
}
);

Categories

Resources