Sorry for asking this question as a new Question. I changed the code as instructed. but still it's not working. Please help me to solve this coding. Thanks !
<div class="label_left_2">
<label class="outputdataField2_Short">Product No</label>
</div>
<div class="input_left_2">
<input list="dropdownproduct" placeholder="Start typing..."
class="inputDataField_Select2_Short" id="dropProduct"
th:field="*{product_id}">
</div>
<datalist id="dropdownproduct">
<option value="0">select product Code</option>
<option th:each="product1 : ${listProducts}"
th:value="${product1.item_Code}" th:text="${product1.name}" />
</datalist>
Ajax Code
$( "#dropProduct" ).select(function() {
// alert( "Handler for .select() called." );
var productId= $( "#dropProduct" ).val();
// alert(' productId'+ productId);
$ajax({
url :'/findProduct2',
**data:{ "productid" : productId },**
dataType:'json',
contentType:'application/json',
success: function(result){
$(discount_Amount).html(result.discount);
}
//}
});
});
Spring Controller Code:-
#RequestMapping("/findProduct2")
ResponseEntity<Product> showProduct2(HttpServletRequest req, Model model) {
System.out.println(" in method.... ");
**String productId = req.getParameter("productId");**
ResponseEntity<Product> responseEntity = new ResponseEntity<Product>(productService.get(productId),
HttpStatus.OK);
return responseEntity;
}
It's probably because you forgot to specify the HTTP method both in the Ajax and Spring controller. I am assuming it's a GET request.
try this for the Ajax
$( "#dropProduct" ).select(function() {
// alert( "Handler for .select() called." );
var productId= $( "#dropProduct" ).val();
// alert(' productId'+ productId);
$ajax({
url :'/findProduct2',
**data:{ "productid" : productId },**
dataType:'json',
type: "GET",
contentType:'application/json',
success: function(result){
$(discount_Amount).html(result.discount);
}
//}
});
});
And this for the Controller
#RequestMapping("/findProduct2", method = RequestMethod.GET)
ResponseEntity<Product> showProduct2(HttpServletRequest req, Model model) {
System.out.println(" in method.... ");
**String productId = req.getParameter("productId");**
ResponseEntity<Product> responseEntity = new ResponseEntity<Product>(productService.get(productId),
HttpStatus.OK);
return responseEntity;
}
Related
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)
});
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>
I'm dynamically adding data to the database using AJAX and displaying them using foreach loop in MVC, I have also added a button to remove the those data using ajax call.
HTML/MVC code:
<div id="divaddrules" class="form-group row">
#try
{
foreach (var item in ViewBag.AdditionalRules)
{
<div class="col-sm-10">
<p style="font-size:large">#item.AdditionalDesc</p>
</div>
<div class="col-sm-2">
<input type="button" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
</div>
}
}
catch (Exception ex){ }
</div>
Now when I click on Remove button it call the following JS code:
function Removeinput(id) {
var datas = {};
datas.addId = id
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: datas,
success: function (result) {
alert(result.id);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
and its passing to this controller:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
I'm getting 500 error on ajax call error.
Can anyone tell me where I'm doing it wrong? Please.. I'm stuck here.
Update:
Attached screenshot: Debug Screenshot
Write your Removeinput function as follows:
function Removeinput(id) {
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: { addId : id},
success: function (response) {
alert(response);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
Then in the controller method:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
AdditionalRules rules = db.AdditionalRules.Find(addId); // Here was the problem. He was pointing to the wrong table that has fixed over team viewer.
db.AdditionalRules.Remove(rules);
db.SaveChanges();
return Json(addId,JsonRequestBehavior.AllowGet);
}
the problem it is missing values on db, in the image you ask to id 25 but return null and you try to remove a item passing null value.
so in your case you need to validate before remove or fix the missing data:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
If(rules == null)
{
//return error msg.
return Json(JsonRequestBehavior.AllowGet);
}
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
make your input type submit, may this was helpful
function deleterelation(id) {
debugger;
if (id > 0)
$.ajax({
url: "/Relations/Delete/" + id,
type: "get",
datatype: "json",
data: { id: id },
success: function (response) {
debugger;
if (response != null) {
$("#txtDName").text(response.name);
$("#DRelationId").val(response.id);
$("#DeleteRelation").modal("show");
}
},
error: function (response) {
$("#DeleteRelationLoading").hide();
$("#DeleteRelation_btn_cancel").show();
$("#DeleteRelation_btn_save").show();
}
});
else
toastr.error("Something went wrong");
}
<input type="submit" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
if this not work plz let me know
I am trying to hit an ajax action "ajaxfactsAction()" in my controller Factoids. But when the ajax call is made I get a 303 error and a redirect to another page.
This is what I have in my template that calls the ajax:
<f:section name="main">
<h1>I am</h1>
<f:form action="">
<f:form.select id="topics" name="topics" options="{categories}" optionValueField="uid" optionLabelField="title" additionalAttributes="{onchange: 'getFacts()'}"/>
<f:form.hidden id="extraids" name="extraids" value="3,4,5" />
<f:form.hidden id="number" name="number" value="3" />
</f:form>
<div>
<div class="factoid1"><f:render partial="Category/Factoid1" /></div>
<div class="factoid2"><f:render partial="Category/Factoid2" /></div>
<div class="factoid3"><f:render partial="Category/Factoid3" /></div>
</div>
<f:flashMessages renderMode="div" />
<script type="text/javascript">
var actionsPathFromViewHelperSetInTheView = '<f:uri.action action="ajaxfacts" controller="Factoid" />';
</script>
</f:section>
and this is the javascript:
function performAjaxCall(Topics, Extraids, Number) {
alert("dddd");
$.ajax({
url: actionsPathFromViewHelperSetInTheView,
data:{
"tx_factoids_interests[uid]":Topics,
"tx_factoids_interests[extraids]":Extraids,
"tx_factoids_interests[number]":Number
},
success:function (data) {
// do something with your json
alert('Load was performed.');
}
});
}
function getFacts(){
performAjaxCall($("#topics").val(), $("#extraids").val(), $("#number").val());
}
and this is my action function:
/**
* action ajaxfacts
*
* #return void
*/
public function ajaxfactsAction() {
echo __LINE__;
die;
}
and my plugin in ext_localconf:
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Seethroughweb.' . $_EXTKEY,
'Interests',
array(
'Factoid' => 'interests, list, show, new, edit, create, update, ajaxfacts',
),
// non-cacheable actions
array(
'Factoid' => 'interests, list, show, new, edit, create, update, ajaxfacts',
)
);
What am I missing to make the action accessible?
The resulting uri looks like this :
xhttp://...xyz.com/index.php?id=111&tx_factoids_interests%5Baction%5D=ajaxfacts&tx_factoids_interests%5Bcontroller%5D=Factoid&cHash=0e805af8af888ebd7fec5e207f64b5f7&tx_factoids_interests%5Buid%5D=5&tx_factoids_interests%5Bextraids%5D=3%2C4%2C5&tx_factoids_interests%5Bnumber%5D=3
the page is is called from is accessible with the first part ie :
xhttp://....xyz.com/index.php?id=111
I am using Typo3 6.2,
Thanks.
PS: javascript version two - made to work like the Arek's answer.
function performAjaxCall(Topics, Extraids, Number) {
alert("performAjaxCall");
$.ajax({
url: $('form').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('form').serialize(), // serializes the form
// data:{
// "tx_factoids_interests[uid]":Topics,
// "tx_factoids_interests[extraids]":Extraids,
// "tx_factoids_interests[number]":Number
// },
success:function (data) {
// do something with your json
alert('performAjaxCall Load was performed.');
}
});
return false;
}
PPS: the request uri from this method now looks like this:
http://...xyz.com/undefinedindex.php?id=111&tx_factoids_interests%5Baction%5D=ajaxfacts&tx_factoids_interests%5Bcontroller%5D=Factoid&cHash=0e805af8af888ebd7fec5e207f64b5f7
and current javascript:
function performAjaxCall( Topics, Extraids, Divid) {
//alert("performAjaxCall");
$.ajax({
type: "POST",
dataType: "json",
url: $('base').attr('href') + $('#form1').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('#form1').serialize(),
// url: actionsPathFromViewHelperSetInTheView,
// data:{
// "tx_factoids_interests[uid]":Topics,
// "tx_factoids_interests[extraids]":Extraids
// },
success:function (data) {
// do something with your json
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
items += "<span class="+ikey+">" + ival + "</span><br/>" ;
});
$(id).html(items);
});
// $(".factoid1").html();
// $(".factoid2").html();
// $(".factoid3").html();
//alert('performAjaxCall Load was performed.');
}
});
}
function getFacts(Divid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid );
return false;
}
and the current template:
<div id="interests">
<f:form action="ajaxfacts" controller="Factoid" id="form1">
<f:form.select id="intereststopics" name="topics" options="{categories}" optionValueField="uid" optionLabelField="content" additionalAttributes="{onchange: 'getFacts(\'#interests\')'}"/>
<f:form.hidden id="interestsextraids" name="extraids" value="2,4,5" />
</f:form>
<div>
<div id="factoid2" class="factoid1"></div>
<div id="factoid4" class="factoid2"></div>
<div id="factoid5" class="factoid3"></div>
</div>
</div>
PPPS: final code
function performAjaxCall( Topics, Extraids, Divid, Formid) {
$.ajax({
type: "POST",
dataType: "json",
url: $(Formid).attr('action'), // now we're using the url generated by Extbase/Fluid
data: $(Formid).serialize(),
success:function (data) {
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
$(id +" ."+ikey).html(ival);
});
});
}
});
}
function getFacts(Divid, Formid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid, Formid );
return false;
}
You didn't set the <f:form action="">.
The calculated cHash is in your case based on the URL generated by <f:uri> which does not contain any information about the other properties you added in your JavaScript. Hereby you're running into the cHash error.
You can prevent that the pageNotFoundHandler is called on a cHash error by disabling $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError'] (Local Configuration).
For more information abount the cHash:
The mysteries of &cHash
The &cHash parameter of frontend plugins might have puzzled quite a few developers but this article will explain how it works and what to avoid in order to make great, reliable plugins with TYPO3.
Solution
Instead of making a custom url you need to use the action from the form generated by Extbase/Fluid.
So your form should look like:
<f:form action="ajaxfacts" controller="Factoid">
And your JavaScript should look like:
$(function() {
$('form').submit(function(e) {
$.ajax({
type: "POST",
url: $('base').attr('href') + $('form').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('form').serialize(), // serializes the form
success:function (data) {
// do something with your json
alert('Load was performed.');
}
});
return false;
});
});
PPPS Final js code:
function performAjaxCall( Topics, Extraids, Divid, Formid) {
$.ajax({
type: "POST",
dataType: "json",
url: $(Formid).attr('action'), // now we're using the url generated by Extbase/Fluid
data: $(Formid).serialize(),
success:function (data) {
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
$(id +" ."+ikey).html(ival);
//items += "<span class="+ikey+">" + ival + "</span><br/>" ;
});
});
}
});
}
function getFacts(Divid, Formid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid, Formid );
return false;
}
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.