Here i am trying to display html content stored in database.When i try it to display in js it gives me "Uncaught ReferenceError: VAR_1 is not defined" in console.
Database:
<div id="dashboard-greeting" class="museo">
<div class="dashboard-greeting-instructions">
<span>Track Progress</span>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Completed</div>
<div class="dashboard-counter-value">VAR_1</div>
</div>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Needed</div>
<div id="subNeeded" class="dashboard-counter-value"></div>
<script>
var subNeedVar = VAR_2 - VAR_1;
$("#subNeeded").html(subNeedVar);
</script>
</div>
</div>
</div>
.js
<div class="tool-button-container">
<input type="submit" name="View" value="LookUp" id="campaignSubmit" class="buOrange large" onClick="validateConfigValues('configKeyName');"/> </div>
function validateConfigValues(id1){
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/adminConfigTest',
data: ({configKeyName:configKeyName, clientId :clientId ,batchId : batchId, languageId : languageId}),
cache: false,
success: function(data) {
var deleteCachingBtn = $('<br><div id="deleteBtn"><Button id="deleteCaching" name="deleteCaching" class="buOrange large" onClick=deleteFromCaching(\'' + configKeyName + '\')> Remove from Cache </div>');
var displayStringAppData = "";
var obj = JSON.parse(data);
$.each(obj, function(index,value) {
displayStringAppData = displayStringAppData+"<br>"+value+"<br>";
alert("displayStringAppData"+displayStringAppData);
});
$("#dbModelWindow").html(displayStringAppData);
if(~data.indexOf("Config is not found in DB also.")) {
} else {
$("#dbModelWindow").append(deleteCachingBtn);
}
$('#dbModelWindow').modal({
"escClose": true,
"overlayClose": true,
"onShow": function() { $.modal.setContainerDimensions();},
});
},
error: function(xhr, textStatus, error){
alert("Error occured. Please try after some time.");
}
});
}
}
.java
#RequestMapping(value="/adminConfigTest", method= RequestMethod.POST)
#PreAuthorize("hasPermission(#adminConfigTest,'ADMIN_TEXT_CONFIG')")
#ResponseBody
public String getAdminConfigTestPost(HttpServletRequest request) throws Exception {
String configKeyName = request.getParameter("configKeyName");
String clientId = request.getParameter("clientId");
String batchId = request.getParameter("batchId");
String language = request.getParameter("languageId");
List<String> arrList = new ArrayList<String>();
try{
Number languageId = null;
if(StringUtils.isBlank(language)){
languageId = RCConstants.ENGLISH_LANGUAGE_ID;
} else {
languageId = Long.parseLong(language);
}
if(StringUtils.isBlank(clientId)){
configManager.getConfigValue(configKeyName, null, "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(clientId) && StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(clientId), "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(batchId), languageId, arrList);
}
} catch (Exception e) {
logger.error(e ,e);
throw e;
}
return JSONSerializer.toJSON(arrList).toString();
}
public String getConfigValue(String configKey, Number batchId, Number languageId, List<String> arrList)throws Exception{
if(arrList != null){
arrList.add("Get config value for : "+ configKey);
arrList.add("batch Id : "+ batchId);
arrList.add("Language : "+ StringUtils.getLanguageCode(languageId));
}
try{
String configKeyValue = null;
String localConfigKeyWithBatchId = batchId+"-"+configKey+"-"+StringUtils.getLanguageCode(languageId);
String queryString = "from Config as model where model.configKeyName = ? and model.batchMetaDataId = ? and model.languageId = ? and model.isDeleted = 0" ;
List<Config> configList = getHibernateTemplate().find(queryString, configKey , batchId ,languageId);
if(!configList.isEmpty()) {
for (Config config : configList) {
configKeyValue = config.getConfigKeyValue();
}
CacheUtil.put(RCConstants.LOCAL_CACHE_WITH_BATCH,localConfigKeyWithBatchId, configKeyValue);
logger.debug("Returning value from db : "+configKey+" - "+configKeyValue);
if(arrList != null){
arrList.add("Db: returning batch and language specific value : " + configKeyValue );
}
}
return configKeyValue;
} catch (RuntimeException re) {
log.error(re, re);
throw re;
}
}
CacheUtil.java
public static Cache localEhCache = null;
public static Cache localEhCacheWithBatchId = null;
public static void put(int cacheNumber, Object key, Object value) {
if (cacheNumber == RCConstants.LOCAL_CACHE) {
localEhCache.put(new Element(key, value));
} else if (cacheNumber == RCConstants.LOCAL_CACHE_WITH_BATCH) {
localEhCacheWithBatchId.put(new Element(key, value));
}
}
But if i rewrite VAR_1 again by erasing VAR_1. It wont show this error.
I googled about this topic but didn't find any solution.
Please help me or suggest me what is going wrong here.
Related
The client-side validation in ASP.Net Core is not working. I have the following code:
#model VeoScheduling.Models.SignInModel
#{
ViewData["Title"] = "SignIn";
}
<div class="login">
<h2>Sign In</h2>
<div>
<form method="post" asp-action="SignIn">
<input type="hidden" asp-for="RedirectUrl" />
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input type="email"
data-bind="value: email" asp-for="Email"
class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"
class="control-label"></label>
<input type="password" asp-for="Password"
data-bind="value: password"
class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Account</label>
<select name="accountSelected" style="margin:5px;width:200px"
data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>
</div>
<br />
#if (Model.Error != "" || Model.Error != null)
{
<p style="color:red">#Html.Raw(Model.Error)</p>
}
</form>
</div>
</div>
#section Scripts{
<script>
var vModel = #Html.Raw(Json.Serialize(Model))
</script>
<script src="~/js/signIn.js" asp-append-version="true"></script>
}
I have also added javascript validation files and I can see they are being loaded when I run but still client-side validation is not working.
I have applied required attribute for both email and password filed. But client-side validation is still not working.
public class SignInModel
{
[Required(ErrorMessage ="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage ="Password is required")]
public string Password { get; set; }
[DisplayName("Forgot Password")]
public bool ForgotPassword { get; set; }
public string RedirectUrl { get; set; }
public string Error { get; set; }
}
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
Below is the js code.
var viewModel = function (model) {
var self = this;
//properties
self.email = ko.observable('');
self.password = ko.observable('');
self.redirectUrl = model.redirectUrl;
self.availableAccounts = ko.observableArray(model.availableAccounts);
self.selectedAccount = ko.observable(null);
//events
self.signOn = function () {
var payloadData = {
'email': self.email(),
'password': self.password(),
'accountSelected': self.selectedAccount()
};
var url = window.location.origin + '/account/SignIn';
CallService("Post", url, payloadData)
.done(function (data) {
var url = window.location.origin + self.redirectUrl;
window.location.replace(url);
});
};
self.accountSelected = function (e, d) {
//alert(self.selectedStack());
};
//methods
self.forgotPassword = ko.observable(false);
self.resetPassword = function () {
$('#loader').show();
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/resetPassword'
$.post(url, payloadData)
.always(function () {
$('#loader').hide();
})
.fail(function (xhr, status, error) {
alert('resetPassword(): error' + xhr.responseText);
})
.done(function (data) {
alert("reset email sent.");
});
};
//ajax
self.getUsersAccounts = function () {
if (self.email() === "")
return;
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/GetAccountsByEmail';
CallService("GET", url, payloadData)
.done(function (data) {
self.availableAccounts.removeAll();
self.availableAccounts(data);
});
};
//computed
self.userChanged = ko.computed(function () {
var userID = self.email();
//alert(userID);
//console.log(userID);
self.getUsersAccounts();
});
self.forgotChecked = ko.computed(function () {
var checked = self.forgotPassword();
var email = self.email();
if (checked) {
if (email === '') {
alert("Please fill in email to reset password");
self.forgotPassword(false);
}
else {
alert("An email link will be sent to your email address.");
self.resetPassword();
self.forgotPassword(false);
}
}
});
//init
if (model.availableAccounts.length === 1) {
self.selectedAccount(model.availableAccounts[0].key);
}
};
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
you could try:
<form id="someform">
......
</form>
<script>
.....
if ($("#someform").valid())
{
//ajax codes
}
else {
return false;
}
</script>
also you could try:
var somevalue = document.getElementById("someId").value;
if (somevalue == null || somevalue == '')
{
$('#somespanId').html("*required");
return false;
}
I ajax post a complex object to a .Net 5.0 controller (not a WebAPI controller). The declaration of the MVC controller and TypeScript are as below. The [HttpPost] Edit action is invoked if I post with <input type='submit' value='Save' />. However, the controller's action is not invoked at all if I post through jQuery .ajax(). The browser console says "POST https://localhost:44381/Question/Edit 400 (Bad Request)". I read many code samples and nothing indicates anything wrong with the code. Does anyone know why?
namespace theProject.Controllers {
public class BaseController: Controller {
protected BaseController(IConfiguration configuration, ILogger logger) {
.......(elided
for brevity)
}
}
}
namespace theProject.Controllers {
//ToDo: [Authorize]
public class QuestionController: BaseController {
public QuestionController(IConfiguration configuration, ILogger < QuestionController > logger): base(configuration, logger) {}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([FromBody] PostbackModel model) {
if (ModelState.IsValid) {
List < UserAnswer > newAnswers = model.NewAnswers;
List < UserAnswer > oldAnswers = model.OldAnswers;
List < UserAnswer > updatedAnswers = model.UpdatedAnswers;
UserAnswer thisAnswer = new();
if (newAnswers != null)
thisAnswer = newAnswers.Find(x => x.StageName != string.Empty);
else if (oldAnswers != null)
thisAnswer = oldAnswers.Find(x => x.StageName != string.Empty);
else if (updatedAnswers != null)
thisAnswer = updatedAnswers.Find(x => x.StageName != string.Empty);
//ToDo: call webapi Question controller to persist the data to database
return RedirectToAction(nameof(Edit), new {
stage = thisAnswer.StageName, personName = thisAnswer.personName, custID = thisAnswer.custID.ToString(), redirectFrom = "Edit"
});
} else {
return RedirectToAction("Index", "Home");
}
}
let postBackModel: AjaxPostbackModel = < AjaxPostbackModel > {};
postBackModel.NewAnswers = newAnswers
postBackModel.OldAnswers = oldAnswers;
postBackModel.UpdatedAnswers = updatedAnswers;
let thisUrl: string = $('form').prop('action');
$.ajax({
type: "POST",
url: thisUrl,
data: JSON.stringify(postBackModel),
contentType: 'application/json; charset=utf-8',
}).done(function(result) {
$('.spinnerContainer').hide();
console.log('postback result', result.message);
console.log('inserted entities', result.insetedEntities);
dialogOptions.title = 'Success';
$('#dialog')
.text('Data is saved. ' + result.message)
.dialog(dialogOptions);
}).fail(function(error) {
console.log('postback error', error);
$('.spinnerContainer').hide();
dialogOptions.title = error.statusText;
dialogOptions.classes = {
'ui-dialog': 'my-dialog',
'ui-dialog-titlebar': 'my-dialog-header'
}
$('#dialog')
.text('Data is not saved')
.dialog(dialogOptions)
});
Since you use [ValidateAntiForgeryToken] in action,you need to add the following code to your ajax to add antoforgery token to header.
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
I was trying to pass a whole object to the jsonresult method. but there are errors that occur. It might be the way I bound it but I'm not sure. I'm new to JS and KOJS. Once the Login button, which is bound to the LogUser method, is clicked, it should call the Authenticate(Employee p) method.
here is my class model
public class Employee
{
[Key]
public long AutoId { get; set; }
[Required]
Display(Name = "Employee ID")]
public string EmployeeId { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string EmployeePassword { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
this is my knockoutjs view model
$(function () {
ko.applyBindings(LoginVm);
});
//VIEW MODEL. MODEL IS BELOW THIS
var LoginVm = {
thisEmp: ko.observable(EmpObject),
LogUser: function () {
var self = this;
//trying to check if thisEmp properties has values by alerting
alert("ID: " + thisEmp.EmployeeId() + " Password: " + thisEmp.EmployeePassword());
$.ajax({
url: '/Employee/AuthenticateUser',
type: 'POST',
dataType: 'json',
data: ko.toJSON(thisEmp),
contentType: 'application/json',
success: function (errorMsg) {
if (errorMsg === '') {
}
}
});
}
};
//MODEL
var EmpObject = {
EmployeeId: ko.observable(''),
EmployeePassword: ko.observable('')
}
this is my view and how I bound the properties
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeeId)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.EmployeeId, new { data_bind="value: thisEmp.EmployeeId()"})
#Html.ValidationMessageFor(model => model.EmployeeId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeePassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.EmployeePassword, new { data_bind="value: thisEmp.EmployeePassword()"})
#Html.ValidationMessageFor(model => model.EmployeePassword)
</div>B
<p>
#*<input type="submit" value="Create"/>*#
<input type="button" value="Login" data-bind="click: LogUser"/>
</p>
</fieldset>
}
this is the error
Uncaught TypeError: Unable to process binding "value: function (){return thisEmp().EmployeeId }"
Message: Cannot read property 'EmployeeId' of undefined
at value (eval at createBindingsStringEvaluator
The error is being thrown because you have defined LoginVm beforeEmpObject. You need to change the order they are declared.
Are you sure this is the code that produced this error? In your view you're binding thisEmp.EmployeeId() but th error says it's unable to bind thisEmp().EmployeeId. I think you tried both of them and the error still persisted. Either way, there is no need to make thisEmp an observable. It's enough that the properties are observables.
So, change your code to:
$(function () {
ko.applyBindings(new LoginVm());
});
//MODEL
var EmpObject = {
EmployeeId: ko.observable(''),
EmployeePassword: ko.observable('')
}
//VIEW MODEL. MODEL IS BELOW THIS
var LoginVm = function() {
var self = this;
self.thisEmp = EmpObject;
self.LogUser = function () {
var self = this;
//trying to check if thisEmp properties has values by alerting
alert("ID: " + self.thisEmp.EmployeeId() + " Password: " + self.thisEmp.EmployeePassword());
$.ajax({
url: '/Employee/AuthenticateUser',
type: 'POST',
dataType: 'json',
data: ko.toJSON(self.thisEmp),
contentType: 'application/json',
success: function (errorMsg) {
if (errorMsg === '') {
}
}
});
}
};
And change the bindings in view to:
#Html.TextBoxFor(model => model.EmployeeId, new { data_bind="value: thisEmp.EmployeeId"})
#Html.PasswordFor(model => model.EmployeePassword, new { data_bind="value: thisEmp.EmployeePassword"})
I am displaying data using auto-complete successfully, I am separating each data by using ',' delimiter.
Now I have a requirement to implement the auto-complete like Liferay Tags for the fields as shown below:
the below is my code :
<aui:script>
AUI().use('autocomplete-list', 'aui-base', 'aui-io-request', 'autocomplete-filters', 'autocomplete-highlighters',
function (A) {
A.io.request('<%=getEntities%>',{
dataType: 'json',
method: 'GET',
on: {
success: function(event, id, obj) {
try {
new A.AutoCompleteList({
allowBrowserAutocomplete: 'false',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />entitiesNames',
resultTextLocator: 'entityName',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
maxResults: 10,
queryDelimiter : ',',
source:this.get('responseData'),
autoLoad:false,
});
} catch(e) {
alert('not working sudheer: ' + e);
}
}
}
});
});
</aui:script>
Also posted in Liferay forum: https://www.liferay.com/community/forums/-/message_boards/message/47095147
In jsp page:
<portlet:resourceURL var="resourceURL"></portlet:resourceURL>
<aui:layout>
<aui:column columnWidth="20" cssClass="lableAlignMent">
<label class="nameLable">Role names</label>
</aui:column>
<aui:column columnWidth="65" cssClass="auto-fields-text-field">
<aui:input name="ListOfRoles" id="ListOfRoles" label="" type="hidden"/>
<aui:input name="ListOfRolesNames" id="ListOfRolesNames" label="" type="hidden"/>
<div id="<portlet:namespace/>rolesDiv" style="">
<aui:input name="roleNames" id="roleNames" title="Enter role names" placeholder="Role name"/>
</div>
</aui:column>
</aui:layout>
<aui:script>
var flag = true ;
var rolesBoxList;
AUI().ready('aui-textboxlist-deprecated', function(A) {
try{
var roles = selectRoles();
rolesBoxList = new A.TextboxList({
contentBox: '#<portlet:namespace />rolesDiv',
input:'#<portlet:namespace />roleNames',
dataSource: roles,
matchKey: 'name',
schema: {
resultFields: ['key', 'name']
},
queryMatchContains:true
}).render();
}catch(e){
//alert('roles'+e);
}
function selectRoles(){
var jsonArray = [];
try{
var url = '<%=resourceURL%>';
jQuery.ajax({
type: 'POST',
url:'<%=resourceURL%>',
data: {
<portlet:namespace />cmd:'roles',
},
dataType:'json',
method:'post',
success: function(msg) {
try{
var jsonArrayTemp=msg.objJsonArray;
for(var i=0;i < jsonArrayTemp.length ;i++ ){
jsonArray.push([jsonArrayTemp[i][0],jsonArrayTemp[i][1]]);
}
}catch(exception){
alert(exception);
}
}
});
}catch(exception){
//alert(exception);
}
return jsonArray ;
}
</aui:script>
In Controller serveResource() method:
Role roleObj=null;
if (cmd.equals("roles")) {
JSONObject objJsonObject = JSONFactoryUtil.createJSONObject();
JSONArray objJsonArray = JSONFactoryUtil.createJSONArray();
System.out.println("IN serve resource roles...");
ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest
.getAttribute(WebKeys.THEME_DISPLAY);
List orgTypeRoleCategoriesList = null;
try {
orgTypeRoleCategoriesList = AttributeLocalServiceUtil
.getOrganizationTypeRoleCategories(themeDisplay
.getLayout().getGroup().getOrganizationId());
} catch (Exception e) {
System.out.println("Exception raised while getting org roles:"
+ e.getMessage());
}
Iterator orgTypeRoleCategoriesObjList = orgTypeRoleCategoriesList
.iterator();
while (orgTypeRoleCategoriesObjList.hasNext()) {
Object[] objectArray = (Object[]) orgTypeRoleCategoriesObjList
.next();
JSONArray childJsonArray = JSONFactoryUtil.createJSONArray();
try {
roleObj=RoleLocalServiceUtil.getRole(Long.valueOf((String) objectArray[0]));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
childJsonArray.put(roleObj.getRoleId());
childJsonArray.put(roleObj.getTitle(themeDisplay.getLocale()));
objJsonArray.put(childJsonArray);
}
objJsonObject.put("objJsonArray", objJsonArray);
System.out.println("objJsonObject:...." + objJsonObject);
resourceResponse.getWriter().print(objJsonObject.toString());
}
I want to show address in my database to an autocomplete aui input field.Everything seems working fine.But im not able to retrive the address number of the record.How to use the on change event of autocomple-list or how can i access the selected item's json object
#Override
public void serveResource( ResourceRequest resourceRequest, ResourceResponse resourceResponse ) throws IOException,
PortletException
{
String cmd = ParamUtil.getString(resourceRequest, "get_address");
String myInputNode = ParamUtil.getString(resourceRequest, "addressAutocomplete");
System.out.println("addressAutocomplete"+myInputNode);
if (cmd.equals("get_address")) {
getUsers(resourceRequest, resourceResponse,myInputNode);
}
}
private void getUsers(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String myInputNode) throws IOException, PortletException {
JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
JSONObject userJSON=null;
try {
List<AddressMaster> userList=AddressMasterLocalServiceUtil.getAllAddressBySearchKey( myInputNode );
for(AddressMaster addressMaster:userList){
userJSON=JSONFactoryUtil.createJSONObject();
userJSON.put("addressNumber",addressMaster.getAdrNummer());
userJSON.put( "address", addressMaster.getAddress())
);
usersJSONArray.put(userJSON);
}
} catch (Exception e) {
}
PrintWriter out=resourceResponse.getWriter();
out.println(usersJSONArray.toString());
System.out.println("usersJSONArray"+usersJSONArray.toString());
}
Jsp File
<portlet:resourceURL var="getAddress">
<portlet:param name="get_address" value="get_address" />
</portlet:resourceURL>
<aui:input id="addressAutocomplete" name="addressAutocomplete" label="group_choose_address" style="width:700px"/>
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
A.io.request('<%=getAddress%>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
//continents=this.get('responseData');
//alert(continents[0].name);
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'true',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace/>addressAutocomplete',
resultTextLocator: 'address',
resultHighlighter:['phraseMatch'],
resultFilters:['phraseMatch'],
render: 'true',
source:this.get('responseData'),
});
}}
});
});
</aui:script>
It's a bit tricky to see exactly what'll be coming, but I think you could do:
var address_ac = new A.AutoCompleteList({... as you have it...});
address_ac.on('select', function (e) {
var selected_node = e.itemNode,
selected_data = e.result;
});
Docs here: http://alloyui.com/versions/1.5.x/api/classes/AutoCompleteList.html#events