AJAX, Thymeleaf Spring dynamic value change - ajax

I'm stuck in the response of ajax spring controller response.
My thymeleaf template code as under:
<div id="categoryContent" class="row no-margin">
<div id="catTitle" class="col-md-12 no-padding">
<h2 th:text="${ctaModule.getCtaSubTitle()}"></h2>
<p class="starting-msrp">Starting at: <span id="price" th:text="${category.getPrice()}"></span></p>
</div>
<h3 class="roof-wheelbase col-xs-12" th:utext="${ctaModule.getCtaDesc()}"></h3>
</div>
<div class="row no-margin category-model-price">
Ajax call:
function get_vehicle_categories()
{
var catController = $('#catTitle h2').html().toLowerCase().replace(/\s+/g, '');
var heightInner = $('#height-inner').find('.active').find('.carousel-caption').html();
var lengthInner = $('#length-inner').find('.active').find('.carousel-caption').html();
$.ajax({
url: './' + catController + '/{height}/{length}',
type: "GET",
dataType: "json",
contentType: 'application/json',
data: {
height: heightInner,
length: lengthInner
},
success: function(response) {
console.log(response);
},
error: function(e) {
console.log(e.Message);
}
});
}
My controller:
#RequestMapping(value = SiteUrls.CATAGORY_PAGE + "/{height}/{length}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String ajaxCategoryVan(#PathVariable("site") String site,
#RequestParam(required = false) String height, #RequestParam(required = false) String length,
Model model) {
AssemblerDTO data = new AssemblerDTO();
data.setSite(site);
if((height == null || height.equals("")) || (length == null || length.equals(""))) {
data.setBody("cargo");
data.setRoof("std");
data.setWheelbase("144");
data.setGvwr("8550");
data.setPowertrain("2500");
} else {
data.setBody("cargo");
if(height.equalsIgnoreCase("Standard Roof")) {
data.setRoof("std");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(height.equalsIgnoreCase("High Roof")) {
data.setRoof("high");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(height.equalsIgnoreCase("High Roof Extended")) {
data.setRoof("superhigh");
data.setGvwr("8550");
data.setPowertrain("2500");
}
if(length.equalsIgnoreCase("144 Wheelbase")) {
data.setWheelbase("144");
data.setGvwr("8550");
data.setPowertrain("2500");
} else if(length.equalsIgnoreCase("170 Wheelbase")) {
data.setWheelbase("170");
} else {
data.setWheelbase("170E");
}
}
setModel(data, model);
return "category";
}
I'm receiving parameters successfully.
I need to change the data as above thymeleaf template.
Kindly help me out.

Related

Problem not displaying success message for each registration with Ajax

I want to do this after the user registers, shows a successful message and the text boxes are empty again and ready for the next registration, but the registration success message is only displayed for the first registration, but I want to Display each registration
public IActionResult submitSingelControlItem(int Projectid,String calender, String ProjectName,String ProjectManagementName, String ajaxControlItem,String ajaxFraindName,int SingelControlState)
{
Hesabrsee hesabrsee = new Hesabrsee();
hesabrsee.ControlDate = ConvertDateTime.ConvertShamsiToMiladi(calender);
hesabrsee.SabtDate = DateTime.Now;
hesabrsee.Projectid = Projectid;
hesabrsee.ProjectName = ProjectName;
hesabrsee.ProjectManagementName = ProjectManagementName;
hesabrsee.FaraindName = ajaxFraindName;
hesabrsee.Deiscreption = ajaxControlItem;
hesabrsee.ControlState = SingelControlState;
_context.Add(hesabrsee);
_context.SaveChanges();
return Json(new { status = "ok" });
}
<script>
$("#btn").on('click', function () {
var ajaxFraindName = $("#ajaxFraindName").val();
var ajaxControlItem = $("#ajaxControlItem").val();
var calender = $("#calender").val();
var SingelControlState = $("#SingelControlState").val();
if (ajaxFraindName == '' || ajaxControlItem == '' || calender == '' || SingelControlState == '') {
alert("لطفا ورودی ها را پر کنید");
}
else {
$.ajax({
type: "Post",
url: '#Url.Action("submitSingelControlItem", "Hasabrsee")',
data: {
'ajaxControlItem': $("#ajaxControlItem").val(),
'ajaxFraindName': $("#ajaxFraindName").val(),
'Projectid': $("#Projectid").val(),
'ProjectName': $("#ProjectName").val(),
'ProjectManagementName': $("#ProjectManagementName").val(),
'calender': $("#calender").val(),
'SingelControlState': $("#SingelControlState").val(),
}
}).done(function (res) {
if (res.status == 'ok') {
$("#ohsnap").removeClass('d-none').removeClass('alert-danger').addClass('alert-success').html('مورد کنترلی با موفقیت ثبت شد');
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
}
setTimeout(function () {
$('#ohsnap').fadeOut('fast');
}, 2000)
});
}
});
</script>
<div id="ohsnap" class="col-md-4 col-xs-12 alert d-none" style="text-align:center;"></div>
Of course, it displays the message only once because you are removing the class from the $("#ohsnap") div and then you are not restoring it.
Try using Toastr to display the popup alert. It is easier to do.
From the Toastr documentation:
Download the CSS and JS files and add them to your project.
Reference the css <link href="toastr.css" rel="stylesheet"/>
Reference the script <script src="toastr.js"></script>
in your .done() function call toastr;
.done(function (res) {
if (res.status == 'ok') {
toastr.success('title-here', 'مورد کنترلی با موفقیت ثبت شد', {
timeOut: 2000,
closeButton: true,
});
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
});

Asp.net core - How to implement realtime using signalR

I am adding a comments part in my project, I would like to use real-time using signalR.
I'm using Ajax for adding comments, and I want to refresh data for all users after the comment inserts into the database.
This is my code in Razor view :
<form asp-action="SendComment" asp-controller="Home" asp-route-subId="#Model.Subject.Id"
asp-route-AccountName="#User.Identity.Name" onsubmit="return jQueryAjaxPost(this);">
<textarea name="comment" id="myTextbox" required class="form-control mb-3" rows="3" cols="1" placeholder="اكتب هنا"></textarea>
<div class="d-flex align-items-center">
<button type="submit" id="myBtn" class="btn bg-blue-400 btn-labeled btn-labeled-right ml-auto"><b><i class="icon-paperplane"></i></b> ارسال</button>
</div>
</form>
Ajax code :
jQueryAjaxPost = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
if (res.isValid) {
$('#view-all').html(res.html)
}
else
$('#form-modal .modal-body').html(res.html);
},
error: function (err) {
console.log(err)
}
})
//to prevent default form submit event
return false;
} catch (ex) {
console.log(ex)
}
}
signalR code (Not finished)
<reference path="../lib/signalr/browser/signalr.js" />
$(() => {
let connection = new signalR.HubConnectionBuilder().withUrl("/signalServer").build();
connection.start();
connection.on("refreshData", function () {
loadData();
});
loadData();
function loadData() {
debugger;
$.ajax({
type: 'GET',
url: '#Url.Action("refreshComments","Home")',
success: function (res) {
$('#view-all').html(res);
}
})
}
});
Code-behind :
var newComment = new CourseComment
{
Comment = comment,
Date = DateTime.Now,
ApplicationUser = user,
SubjectId = subId,
CreatedDate = DateTime.Now
};
_courseCommnt.Entity.Insert(newComment);
await _courseCommnt.SaveAsync();
await _signalR.Clients.All.SendAsync("refreshData");
_toastNotification.AddSuccessToastMessage("تم ارسال التعليق بنجاح");
var courseComments = await _courseCommnt.Entity.GetAll().Include(a => a.ApplicationUser)
.Where(a => a.SubjectId == subId).OrderByDescending(a => a.Date).AsNoTracking().ToListAsync();
var vm = new HomeViewModel
{
CourseComments = courseComments
};
return Json(new
{
isValid = true,
html = Helper.RenderRazorViewToString(this, "_SubjectComments", vm)
});

No response from POST request Spring boot - AJAX

I try to send data from AJAX POST request and don't get an answer, but if I send the exact same request with POSTMAN I do get a response. I don't know what is causing this.
REST Spring boot:
#RestController
public class UsuarioRest {
UsuarioController usuarioController = new UsuarioController();
String token = null;
Usuario usuario = null;
#GetMapping(value = "/hola")
public ResponseEntity<?> login(#RequestBody Usuario user) {
token = usuarioController.login(user.getUser(), user.getPassword());
if (token != null) {
usuario = new Usuario(user.getUser(), user.getPassword());
usuario.setToken();
return new ResponseEntity<Usuario>(usuario, HttpStatus.OK);
} else {
return new ResponseEntity<Error>(new Error(), HttpStatus.BAD_REQUEST);
}
}
AJAX POST:
$(document).ready(
function() {
// SUBMIT FORM
$("#btnEnviar").submit(function(event) {
// Prevent the form from submitting via the browser.
event.preventDefault();
ajaxPost();
});
function ajaxPost() {
// PREPARE FORM DATA
var User = {
id:0,
user : $("#user").val(),
password : $("#password").val(),
token:0
}
console.log(formData);
// DO POST
$.ajax({
type : "GET",
contentType : "application/json",
url : "hola",
data : JSON.stringify(User),
dataType : 'json',
success : function(result) {
console.log(result);
if (result.status == "success") {
$("#resultado").html(
"" + result.data.token
+ "Post Successfully! <br>"
+ "---> Congrats !!" + "</p>");
} else {
console.log(result);
$("#resultado").html("<strong>Error</strong>");
}
},
error : function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
})
HTML:
<body>
<form id="login">
<input type="text" id="user">
<input type="text" id="password">
<button type="submit" id="btnEnviar" >Enviar</button>
</form>
<div id="resultado">
<button id="hola"></button>
</div>
</body>

How can I get the dynamic value to my id variable in javascript?

I have been trying to get the different values in my id variable in javascript so that I can fetch the data according to the id I hover.
I have following code inside the <script></script>
$(document).ready(function() {
$('.stambha-img').hide();
$(".stambha-cat").hover(function() {
var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value");
$.ajax({
url: '/ajaxCat.php',
type: 'POST',
data: {
id: id
},
success: function(response){
if (typeof(response) != 'object') {
response = $.parseJSON(response);
}
if (response.status.status == true) {
var html_option = ""
$.each(response.body, function(key, value) {
var newsImage = "";
if(value.image === ""){
newsImage = "<?php echo FRONT_IMAGES_URL.'shikshak.jpg' ?>";
} else {
newsImage = value.image;
}
html_option += "<div class='col-md-3'><div class='stambha-img'><img class='img-responsive' src='" + newsImage + "'></div></div>";
});
html_option += "<div>";
$('#catAjax').html(html_option);
} else if(response.status.status == false){
var amount_np = 'hello';
$('#catAjax').html('<div class="container text-center" id="c404"><div class="row"><div class="col-md-6 col-sm-12 offset-md-3 c404"><h5 style="color:#DB4729"><strong>माफ गर्नुहोस्! यस कोटीमा कुनै समाचार छैन।</strong></h5></div></div></div>');
}
}
});
$('.stambha-img').show();
}),
$(".stambha-cat").mouseenter(function() {
$(".stambha-img").show();
});
$(".stambha-cat").mouseleave(function() {
$(".stambha-img").hide();
id = "";
});
});
I want to erase the value of id when the mouseleave event occur so that when I hover to the next item I can get the id of other category.
And, I have the following code inside the list:
<li class="stambha-cat" value="<?php echo $necessary->id ?>"><a class="boldtitle" href="http://<?php echo $necessary->url ?>" target="_blank"><strong><?php echo $necessary->title ?></strong></a></li>
Update: When I hover over another category, I get the same category id. Is that because var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value"); giving the value of first category inside the class "stambha-cat"?
Replacing var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value"); with var id = $(this).attr('value'); worked for me. See the full code below:
$(document).ready(function() {
$('.stambha-img').hide();
$(".stambha-cat").hover(function() {
var id = document.getElementsByClassName("stambha-cat")[0].getAttribute("value");
$.ajax({
url: '/ajaxCat.php',
type: 'POST',
data: {
id: id
},
success: function(response){
if (typeof(response) != 'object') {
response = $.parseJSON(response);
}
if (response.status.status == true) {
var html_option = ""
$.each(response.body, function(key, value) {
var newsImage = "";
if(value.image === ""){
newsImage = "<?php echo FRONT_IMAGES_URL.'shikshak.jpg' ?>";
} else {
newsImage = value.image;
}
html_option += "<div class='col-md-3'><div class='stambha-img'><img class='img-responsive' src='" + newsImage + "'></div></div>";
});
html_option += "<div>";
$('#catAjax').html(html_option);
} else if(response.status.status == false){
var amount_np = 'hello';
$('#catAjax').html('<div class="container text-center" id="c404"><div class="row"><div class="col-md-6 col-sm-12 offset-md-3 c404"><h5 style="color:#DB4729"><strong>माफ गर्नुहोस्! यस कोटीमा कुनै समाचार छैन।</strong></h5></div></div></div>');
}
}
});
$('.stambha-img').show();
}),
$(".stambha-cat").mouseenter(function() {
$(".stambha-img").show();
});
$(".stambha-cat").mouseleave(function() {
$(".stambha-img").hide();
id = "";
});
});

Ajax Login from MVC

I have an MVC project that uses the inbuilt forms authentication (which talks to the MDF database stored in App_data). I want to change the login form to be the Ajax login form so that I can take advantage of the "onSuccess" and "onFailure" options.
Does anyone have a working example of how I would achive this as I've tried previuosly but I can't get the form to authenticate it just does nothing. I think I may have missed a step so any help is appreciated.
Example code would also be benificial. Please find my current code below.
The login view
#model MyProject.Models.LoginViewModel
#using (Ajax.BeginForm("Login", "Account", null, new AjaxOptions
{
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
OnFailure = "OnFailure",
OnComplete = "OnComplete",
HttpMethod = "POST",
UpdateTargetId = "target"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Login Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
</li>
</ol>
<input type="submit" value="Login" />
</fieldset>
}
Here is the login controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult ValidateUser(string userid, string password,
bool rememberme)
{
LoginStatus status = new LoginStatus();
if (Membership.ValidateUser(userid, password))
{
FormsAuthentication.SetAuthCookie(userid, rememberme);
status.Success = true;
status.TargetURL = FormsAuthentication.
GetRedirectUrl(userid, rememberme);
if (string.IsNullOrEmpty(status.TargetURL))
{
status.TargetURL = FormsAuthentication.DefaultUrl;
}
status.Message = "Login attempt successful!";
}
else
{
status.Success = false;
status.Message = "Invalid UserID or Password!";
status.TargetURL = FormsAuthentication.LoginUrl;
}
return Json(status);
}
Here is the login view model
public class LoginStatus
{
public bool Success { get; set; }
public string Message { get; set; }
public string TargetURL { get; set; }
}
Script on the page for handling the form
$(document).ready(function () {
$("#login").click(function () {
$("#message").html("Logging in...");
var data = {
"UserName": $("#userid").val(),
"Password": $("#password").val(),
"RememberMe": $("#rememberme").prop("checked")
};
$.ajax({
url: "/Home/Index",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (status) {
$("#message").html(status.Message);
if (status.Success)
{
window.location.href = status.TargetURL;
}
},
error: function () {
$("#message").html("Error while authenticating user credentials!");
}
});
});
});
I've an extensions (MvcNotification) that put into ViewData or TempData messages to display.
To complement this, my post actions return "ERROR" or "OK" and i use those messages inside the ajax form OnSuccess.
MessageType
public enum MessageType
{
Success,
Warning,
Error,
Info
}
AjaxMessagesFilter
/// <summary>
/// If we're dealing with ajax requests, any message that is in the view data goes to the http header.
/// </summary>
public class AjaxMessagesFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewData = filterContext.Controller.ViewData;
var response = filterContext.HttpContext.Response;
foreach (var messageType in Enum.GetNames(typeof(MessageType)))
{
var message = viewData.ContainsKey(messageType)
? viewData[messageType]
: null;
if (message != null) // We store only one message in the http header. First message that comes wins.
{
response.AddHeader("X-Message-Type", messageType.ToLower());
response.AddHeader("X-Message", HttpUtility.HtmlEncode(message.ToString()));
return;
}
}
}
}
}
ControllerExtensions
public static class ControllerExtensions
{
public static ActionResult ShowMessage(this Controller controller, MessageType messageType, string message, bool showAfterRedirect = false, bool UseJson = false)
{
var messageTypeKey = messageType.ToString();
if (showAfterRedirect)
{
controller.TempData[messageTypeKey] = message;
}
else
{
controller.ViewData[messageTypeKey] = message;
}
if (UseJson)
return new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
else
return new ContentResult() { Content = "ERROR" };
}
public static ActionResult ShowMessage(this ControllerBase controller, MessageType messageType, string message, bool showAfterRedirect = false, bool UseJson = false)
{
var messageTypeKey = messageType.ToString();
if (showAfterRedirect)
{
controller.TempData[messageTypeKey] = message;
}
else
{
controller.ViewData[messageTypeKey] = message;
}
if (UseJson)
return new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
else
return new ContentResult() { Content = "ERROR" };
}
public static ActionResult EmptyField(this Controller controller, string FieldName, bool IsJson = false)
{
controller.ShowMessage(MessageType.Info, String.Format("O campo \"{0}\" é de carácter obrigatório.", FieldName));
return IsJson == false ? (ActionResult)new ContentResult() { Content = "ERROR" } : (ActionResult)new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
To call the extension inside the controller:
this.ShowMessage(MessageType.Error, "An error has occurred");
if you want to redirect after the message is thrown, you need to add true in the last parameter.
this.ShowMessage(MessageType.Error, "An error has occurred", true);
Note: I created the EmptyField method to give a standart message when some field is empty.
Action Example (LoginPost)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginPost(LoginViewModel model, string returnUrl, bool Relogin = false)
{
returnUrl = string.IsNullOrEmpty(returnUrl) || string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl;
if (string.IsNullOrEmpty(model.UserName))
return this.EmptyField(Resource_General.UserName);
if (string.IsNullOrEmpty(model.Password))
return this.EmptyField(Resource_General.Password);
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = SignInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var user = db.Users.FirstOrDefault(x => x.UserName == model.UserName);
if (!user.IsActive)
{
AuthenticationManager.SignOut();
this.ShowMessage(MessageType.Error, Messages.LockedOutUser);
return Content("ERROR");
}
if (Url.IsLocalUrl(returnUrl))
return Content(returnUrl);
else
return Content("/Home");
case SignInStatus.LockedOut:
this.ShowMessage(MessageType.Error, Messages.LockedOutUser);
return Content("ERROR");
case SignInStatus.RequiresVerification:
case SignInStatus.Failure:
default:
this.ShowMessage(MessageType.Error, Messages.WrongPassword);
return Content("ERROR");
}
}
Ajax Form
#using (Ajax.BeginForm("LoginPost", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, new AjaxOptions { OnSuccess = "OnSuccess" }, new { #id = "login-form" }))
{
#Html.AntiForgeryToken()
<div class="network-login-fields">
<div class="form-group">
<div class="input-group col-xs-12">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", placeholder = Resource_General.UserNamePlaceHolder, name = "loginname", autofocus = "true" })
</div>
</div>
<div class="form-group">
<div class="input-group col-xs-12">
#Html.PasswordFor(m => m.Password, new { #class = "form-control", placeholder = Resource_General.PasswordPlaceHolder, name = "password" })
</div>
</div>
<div class="network-login-links">
<button class="btn btn-default"><i class="fa fa-sign-in"></i> #Resource_General.Login</button>
</div>
</div>
}
Javascript
function OnSuccess(data) {
if (data != "ERROR") {
window.location.href = data;
}
}
Here in the javascript, you need to handle the ajax form OnSuccess and do something if the response is "OK" or "ERROR".
In your main javascript file you need to include this:
Handle Messages
// START Messages and Notifications
function handleAjaxMessages() {
$(document).ajaxStart(function () {
Openloading();
}).ajaxComplete(function (e, xhr, settings) {
CloseLoading();
}).ajaxSuccess(function (event, request) {
checkAndHandleMessageFromHeader(request);
}).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (thrownError !== "abort") {
CloseLoading();
NotifyError();
}
OnInit();
});
}
function checkAndHandleMessageFromHeader(request) {
var msg = request.getResponseHeader('X-Message');
if (msg) {
var title = NotifyHeader(request.getResponseHeader('X-Message-Type'));
Notify(msg, title, request.getResponseHeader('X-Message-Type'));
}
}
function NotifyHeader(type) {
console.log(type);
var title = "";
if (type == "error")
title = CustomScriptsLocales.ErrorTitle;
if (type == "success")
title = CustomScriptsLocales.SuccessTitle;
if (type == "warning")
title = CustomScriptsLocales.WarningTitle;
if (type == "info")
title = CustomScriptsLocales.InfoTitle;
console.log(title);
return title;
}
function Notify(message, title, type) {
if (title == null || title == "" || title == undefined) {
title = NotifyHeader(type);
}
PNotify.desktop.permission();
var notice = new PNotify({
title: title,
text: decodeHtml(message),
nonblock: {
nonblock: true,
nonblock_opacity: .55
},
buttons: {
closer: true,
},
desktop: {
desktop: false,
},
hide: true,
type: type,
delay: 2000,
insert_brs: true,
remove: true,
});
}
function NotifyError() {
Notify(CustomScriptsLocales.ErrorMessage, CustomScriptsLocales.ErrorTitle, "error");
}
// END Messages and Notifications
And call it inside a ready function:
$(document).ready(function () {
handleAjaxMessages();
}
Note: I use the PNotify plugin to show notifications. If you don't want notifications just exclude all this javascript "Handle Messages".

Resources