Spring Thymealef Ajax update fragmenet - ajax

I'm using spring boot MVC, and have a part that I make an ajax request to update a collection of products for merchandise shipment, but when I post it is displaying json on the screen instead of updating the fragment:
<th:block th:if="${expedicao.tipoRegistro eq 'A' or expedicao.tipoRegistro eq 'X'}">
<form action="#" th:action="#{/expedicao/buscaprod}" method="post"
name="formBusca">
<input type="hidden" th:name="${_csrf.parameterName}"
th:value="${_csrf.token}" /> <label th:text="Ean13">Ean13</label>
<input type="radio" name="tipoCod" id="tipoCod" value="ean13" /> <label
th:text="Dun14">Dun14</label> <input type="radio" name="tipoCod"
id="tipoCod" value="dun14" /> <input type="text"
name="FieldCodigo" class="form-control" placeholder="Codigo Barras"
id="FieldCodigo" value="" autofocus="autofocus" required="required" />
<input type="hidden" name="id_expedicao" id="id_expedicao"
th:value="${expedicao.id}" />
<button type="submit" value="Buscar">Buscar</button>
</form>
</th:block>
<div th:fragment="info-success" xmlns:th="http://www.thymeleaf.org" th:remove="tag">
<div class="modal-body row" id="coleta">
<div th:replace="expedicao/coleta::coleta"></div>
</div>
</div>
</div>
this is my ajax
<th:block layout:fragment="scripts">
<script th:inline="javascript">
/*<![CDATA[*/
$(function() {
$.ajaxSetup({
headers : {
'X-CSRF-Token' : $('meta[name=_token]').attr('content')
}
});
$('form#formBusca').submit(
function(e) {
e.preventDefault();
$.ajax({
type : "POST",
contentType : "application/json",
url : 'expedicao/buscaprod',
data : $('form#formBusca').serialize(),
dataType : 'json',
success : function(result) {
if(result.status == "Done"){
carregarColeta(result.data.id);
if (result.data.situacao == 'B'
|| result.data.situacao == 'C') {
$('form#formBusca').remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
$('input[name=FieldCodigo]').val('');
});
});
function carregarColeta(idexpedicao) {
$.ajax({
method : 'POST',
url : 'expedicao/detalhe',
data : {
'id_expedicao' : idexpedicao
},
success : function(retorno) {
$('#coleta').empty().html(retorno);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
}
when a execute the post method it go to my controller execute the logic and return the json of the object updated, and instead of update the fragment calling the JS function carregaExpedicao.. its dislpay the json on the screen, and change the url
this is my controller
#Controller
public class ExpedicaoController {
#RequestMapping(value = "/expedicao/buscaprod", method = RequestMethod.POST)
#ResponseBody
public Response updateProdutoColetado(
#RequestParam(name = "id_expedicao") String id_expedicao,
#RequestParam(name = "FieldCodigo") String FieldCodigo,
Model model, HttpSession session) {
//Minhas regras
model.addAttribute("expedicao", expedAndamento);
return new Response("Done", expedAndamento);
}
#RequestMapping(value = "/expedicao/detalhe")
public String detalhe(#RequestParam(name = "id_expedicao") String id_expedicao, Model model, HttpSession session) {
model.addAttribute("expedicao", expedAndamento);
return "expedicao/coleta";
}
}
Fixed:
error 1 => id on the form
error 2 => missing csrf param on ajax

Related

ajax post failed but controller & db data ok

im posting data to controller with partailview the controller receive valid data & store it in my DB but:
im getting ajax failed Msg.
im not getting a TempData displayed as expected ( i have one for results OK and else for error).
Im not sure where to put my finger on .
Index View
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
function SubmitREgNews() {
var data = {
userName: $("#name").val(),
UserMail: $("#email").val(),
TermsOk: $("#bOk").val(),
};
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
}
Partial view
#if (#TempData["ErrorMes"] != null)
{
#TempData["ErrorMes"]
}
#if (#TempData["regOk"] == null)
{
<div class="row">
<div class="col-md-4">
<form id="studenteForm" novalidate class="needs-validation">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="userName" class="control-label"></label>
<input asp-for="userName" class="form-control" id="name" required />
</div>
<div class="form-group">
<label asp-for="UserMail" class="control-label"></label>
<input asp-for="UserMail" type="email" class="form-control" id="email" /> </div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" id="bOk" asp-for="TermsOk" /> #Html.DisplayNameFor(model => model.TermsOk)
</label>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" onclick="SubmitREgNews();">Add </button>
</div>
</form>
</div>
</div>
</div>
}
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
controller
public IActionResult _RegNews()
{
return PartialView();
}
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews )
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if ( ModelState.IsValid && IsNewUser==null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return View("home/index");
}
else
{
TempData["ErrorMes"] = "You are allready register";
}
return PartialView("_RegNews", joinNews);
}
The reason you are getting ajax failed Msg may be that you are returning the wrong path "home/index". Paths in one controller that call a page in another controller should use "../home/index".
Also, Ajax doesn't change page elements. If you want to redirect to another page you can use Url.Action.
Like this:
Controller:
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews)
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if (ModelState.IsValid && IsNewUser == null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return Json(new { redirectUrlOne = Url.Action("Index", "Home")});
}
else
{
TempData["ErrorMes"] = "You are allready register";
return Json(new { redirectUrlTwo = Url.Action("_RegNews", "NewsLetter") });
}
}
And your ajax:
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function (result) {
alert('Successfully received Data ');
if (result.redirectUrlOne !== undefined) {
window.location.replace(result.redirectUrlOne);
} else {
window.location.replace(result.redirectUrlTwo);
}
console.log(result);
},
error: function (error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
If you don't want to use Url.Action, you can also do not use Ajax, using the Form Tag Helper to submit data is the same. You can check the details in this official document.

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

ajaxSubmit / function(data) call happening twice

I am trying to upload a large file and having issues of submit happening twice.
But not for small file sizes.
The $("#fileform").ajaxSubmit({ call seems to be happening twice or multiple times instead of once. Or the submit 'success : function(data) {' .
Not sure. I am able to see the details in 'commands_cvs_grpupload.jsp' twice.
HTML:
<form id="fileform" method="post" align="left">
<input id="importFile" name="importFile" type="file" onkeydown="return false"
onpaste="return false" ondragenter="return false"/>
<input id= "errorRecords" name = "errorRecords" type="hidden"/>
<input id= "type" name = "type" value="BULK_UPLOAD" type="hidden"/>
<input name="import" type="button" onClick="importCSV();" value="Import CSV"/>
Script for importCSV():
function importCSV(){
if(checkFileIsNull()){
$("#requiredFile").css("color","#000000");
$("#requiredFileType").css("color","#000000");
$("#gridWrapper").hide("slow");
configDisplayMessage("displayMessage","White");
$("#displayMessage").html("");
$("#ui-progressbar-value").html("");
$("#statusmessage").html("");
$( "#progressbar" ).progressbar({
value: 0
});
$("#processDiv").show();
$("#progressbar").show();
$("#statusmessage").show();
$("#ui-progressbar-value").show();
$("#progressbar").html("Waiting...");
// submit file to SBS; command is callaSBSImport
submitFileToSBS();
// get status for SBS ; command is callSBSStatus
getStatusFromSBS();
startProcess = setInterval("getStatusFromSBS()",3000);
}else{
$("#gridWrapper").hide("slow");
$("processDiv").hide();
$("#progressbar").hide();
$("#statusmessage").hide();
$("#ui-progressbar-value").hide();
}
}
Script for submitFileToSBS()
function submitFileToSBS(){
$("#fileform").ajaxSubmit({
type : "post",
url : "framework/commands_cvs_grpupload.jsp",
dataType:"json",
data : "Command=callSBSGroup&Service=ComplianceValidation&Method=uploadGroupings",
success : function(data) {
setProcessBar(100,"Process is done.");
clearInterval(startProcess);
errorRecords = Array();
var list = "";
var stringBuilder = "";
/*MY CODE*/
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
/*MY CODE*/
}
});
}

Internal Server Error on ajax GET request in Spring MVC

Hi everyone i'm new to spring MVC so i have little idea about the framework. All I'm trying to do is refresh a div in my view with items filtered by a hibernate query, which prints correctly to standard out.
For some reason I'm not aware of I get a 500; Internal server error when i try a get request via ajax.
I changed the return type in the controller, my original idea was to use the default index controller with an optional parameter.
View:
<div id="itemListContainer">
<c:if test="${!empty items}">
<c:forEach items="${items}" var="item">
<c:url value="/showImage.htm" var="url">
<c:param name="id" value="${item.id}" />
</c:url>
<div id="${item.id}" class="col-lg-2 col-md-3 col-xs-6 thumb">
<img class="img-responsive" src="${url}" alt="${item.name}">
</div>
<input id="name_${item.id}" type="hidden" value="${item.name}">
<input id="name_${item.id}" type="hidden" value="${item.review}">
</c:forEach>
</c:if>
<c:if test="${!empty itemList}">
<h1>Nothing found</h1>
</c:if>
</div>
JS File
function filterItems(value) {
$("#itemListContainer").empty();
$.ajax({
method: "GET",
//dataType: "json",
url: "filterItems.htm",
data: {
type: value
},
success: function (data) {
if (data) {
$("#itemListContainer").html(data);
} else {
console.log(xhr.responseText);
alert("failure");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
Controller:
#RequestMapping(value = "/filterItems", method = RequestMethod.GET)
public #ResponseBody List<Item> filterItems(#RequestParam(value = "type", required = false) String type) {
List<Item> items = new ArrayList<Item>();
try {
items = itemDao.getItems(type);
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
Any help will be greatly appreciated. Thanks in advance!!
Once again, when it comes my little experience with hibernate, the error has nothing to do with Javascript, controller o DAO but with entity mapping.
My Item entity had an association with a User entity, and had to specify between lazy and eager loading of the association. In my case it was solved by adding lazy="true" to my xml file.

Post datetime to controller

I am trying to send date to controller using ajax but get's null. why?
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
$.ajax({
url: "/Home/GetData",
type: "POST",
data: JSON.stringify($('#datetimepicker1').data('DateTimePicker').date()),
contentType: "application/json",
success: function (result) { alert('Done') },
error: function (r, e, s) { alert(e) }
});
});
</script>
</div>
</div>
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetData(string test)
{
return View();
}
}
You not passing a name/value pair back to the controller method that matches the parameter name (test) and the is no need to stringify the data. Change the ajax script to
$.ajax({
url: '#Url.Action("GetData", "Home")', // don't hard code your url's
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date() },
// contentType: "application/json", delete this
success: function (result) { alert('Done') },
error: function (r, e, s) { alert(e) }
});
And since you posting a DateTime value the controller method should be
[HttpPost]
public ActionResult GetData(DateTime test)
{
return View();
}
This assumes the the date value is in a format that matches the server culture, or in ISO format ('yyyy-MM-dd HH:mm'), for example by using
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
Note that your method is returning a view, but you not doing anything with the html you return (just displaying an alert)

Resources