autocomplete to avoid tab operation for textbox - javascript

I am using Autocomlete to show the list of location which come from database. User get the list as expected. but instate selecting from list user just click on the tab button and control going to next button. I want to avoid TAB operation here.Any suggestion how i will do that .
Here is my function :
$(document).ready(function () {
src = 'LocationHandler.ashx';
$('#txtLocationName').autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term,
type: $("#ddlDivision1").val()
},
success: function (data) {
Object.keys = Object.keys || function (o, k, r) { r = []; for (k in o) r.hasOwnProperty.call(o, k) && r.push(k); return r }
if (Object.keys(data).length == 0) {
$('#txtLocationName').val('');
alert('Location must be selected from the options.');
}
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
My Handler class looks like
public class LocationHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string term = context.Request["term"] ?? "";
string type = context.Request["type"] ?? "";
// type = "FM";
List<string> listLocationNames = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["EGLFormsDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spIARLocationNames", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#locType",
Value = type
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listLocationNames.Add(rdr["Name"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(listLocationNames));
}
public bool IsReusable
{
get
{
return false;
}
}
}

this is how i solve this.
$("#txtLocationName").keydown(function (evt) {
var keyCode = evt.keyCode || evt.which;
if (keyCode == 9) {
//evt.preventDefault();
//alert("TAB not allowed111111. Please select business unit number or name from Search box. ");
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
if (evt.key === "Tab")
{
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
});

Related

javascript function pass object with null values

I am doing master/detail using this article as a guide, my case is a little different as I have five different details for single master table and each one with totally different details/columns. I want my users to enter all rows in selected detail table and pass these rows with the master to the controller, but passed parameter is always null. I searched a lot without success.
Solution in this post did not work for me and a couple of others in different forums.
Here is my code:
//JobOrderMaster Action:
[HttpPost]
public ActionResult JobOrderMaster(WorkOrder objJobOrder, string btnPrevious, string btnNext)
{
ViewBag.Project_Id = new SelectList(db.Projects, "Project_Id", "Project_Name_e");
if (btnNext != null)
{
if (ModelState.IsValid)
{
workOrderId = Guid.NewGuid();
JobOrderViewModel objWorkOrder = GetJobOrder();
objWorkOrder.WorkOrder_Id = workOrderId;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.Created_By = User.Identity.GetUserName();
objWorkOrder.Descriptions = objJobOrder.Descriptions;
ViewBag.WorkOrderId = objWorkOrder;
switch ((int)objJobOrder.WorkOrder_Type)
{
case 1: return View("JobOrderDetails");
case 2: return View("InHouseMaintenance");
case 3: return View("CustomerSideMaintenance");
case 4: return View("SiteSurvey");
case 5: return View("Installation");
default: return View("JobOrderDetails");
}
}
}
return View();
}
//JobOrderDetails Action:
//string expenseMaster;
[HttpPost]
public ActionResult JobOrderDetails(WorkOrderDetail[] objWorkOrderDetail)
{
WorkOrder objWorkOrder = new WorkOrder();
WorkOrderDetail details = new WorkOrderDetail();
JobOrderViewModel objJobOrder = GetJobOrder();
if (objJobOrder.WorkOrder_Id != null)
{
objWorkOrder.WorkOrder_Id = objJobOrder.WorkOrder_Id;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.Descriptions = objJobOrder.Descriptions;
objWorkOrder.Type_Id = objJobOrder.Type_Id;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.WorkOrder_Status = objJobOrder.WorkOrder_Status;
objWorkOrder.WorkOrder_Priority = objJobOrder.WorkOrder_Priority;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.Created_By = User.Identity.GetUserName();
db.WorkOrders.Add(objWorkOrder);
}
int detailId = 1;
//if (btnNext != null)
//{
if (ModelState.IsValid)
{
foreach (var item in objWorkOrderDetail)
{
details.WorkOrder_Id = objWorkOrder.WorkOrder_Id;
details.Category_Id = item.Category_Id;
details.Detail_Id = detailId;
details.Qty = item.Qty;
db.WorkOrderDetails.Add(details);
detailId++;
}
try
{
db.SaveChanges();
RemoveJobOrder();
return View("Index");
}
catch (DbUpdateException ex)
{
string message = "";
UpdateException updateException = (UpdateException)ex.InnerException;
SqlException sqlException = (SqlException)updateException.InnerException;
foreach (SqlError error in sqlException.Errors)
{
message = string.Format("{0} Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, error.Number
, error.Message
, error.LineNumber);
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
catch (DbEntityValidationException ex)
{
string message = "";
foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
{
//Get entry
DbEntityEntry entry = item.Entry;
string entityTypeName = entry.Entity.GetType().Name;
//Display or log error messages
foreach (DbValidationError subItem in item.ValidationErrors)
{
message = string.Format("{0}Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, subItem.ErrorMessage
, entityTypeName
, subItem.PropertyName);
}
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
}
//}
return View();
}
//My javascript functions
function btnFinish(details) {
//alert(JSON.stringify(details));
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("JobOrderDetails")',
data: JSON.stringify({ objWorkOrderDetail: details }),
success: function (result) {
//location.reload();
},
error: function (err) {
if (err != null) {
alert('Error: ' + err.Message);
}
}
});
}
$("#btnFinish").click(function (e) {
e.preventDefault();
var claimArr = [];
claimArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
claimArr.push({
categoryId: $(this).find('td:eq(0)').html(),
descriptions: $(this).find('td:eq(1)').html(),
quantity: $(this).find('td:eq(2)').html()
});
});
var data = JSON.stringify(claimArr);
//alert(data);
$.when(btnFinish(data)).then(function (response) {
window.location.href = "../JobOrder/Index";
//console.log(response);
}).fail(function (err) {
console.log(err.Message);
window.location.href = "../JobOrder/Index";
});
});
});
action screenshot shows null values
alert msg shows object received ok in js function
The problem is that You don't have the same names of properties in JSON (JavaScript side) and your class WorkOrderDetails in C#:
WorkOrderDetails
JSON
Category_Id
categoryId
Descriptions
descriptions
Qty
quantity
Make the same names in two of these types and it should be ok.
For example:
WorkOrderDetails
JSON
categoryId
categoryId
descriptions
descriptions
quantity
quantity

itext7 - equivalent method for getJavascript in pdfReader class in itext7

Is there any equivalent method for getJavascript in pdf reader in itext7? we are looking for sanitizing the pdf document for malicious content using itext7.
As far as I can see there is not a dedicated method for that in iText 7.
Essentially, though, the old PdfReader.getJavaScript() method merely looked for the JavaScript name tree and put all the values into a string buffer.
You can output these values like this in iText 7:
PdfNameTree javascript = pdfDocument.getCatalog().getNameTree(PdfName.JavaScript);
Map<String, PdfObject> objs2 = javascript.getNames();
for (Map.Entry<String, PdfObject> entry : objs2.entrySet())
{
System.out.println();
System.out.println(entry.getKey());
System.out.println();
PdfObject object = entry.getValue();
if (object.isDictionary()) {
object = ((PdfDictionary)object).get(PdfName.JS);
if (object.isString()) {
System.out.println(((PdfString)object).getValue());
} else if (object.isStream()) {
System.out.println(new String(((PdfStream)object).getBytes()));
}
}
System.out.println();
}
(ShowDocumentLevelJavaScript test testREJECT_ContainsJavaScript)
Obviously you can in a similar manner collect the pieces of JavaScript into some string buffer.
In a comment James claimed
I tried using (and extending) your answer but cannot detect the JavaScript popup that fires when I open a sample PDF
Applying the above code to the PDF file provided by #James I get the output:
e.pdf Freeware Hinweis
if (app.viewerVersion>=5)
{
var result=app.alert(
"Diese Datei wurde mit der Freeware Version von CIB e.pdf erzeugt.\n\nMöchten Sie nähere Informationen?"
, 3
, 2
, "e.pdf Freeware Hinweis"
);
if (result==4)
getURL("http://www.cib.de/deutsch/products/pdfplugin/epdfbeta.asp", false);
}
The JavaScript popup can clearly be seen as an app.alert call here. Thus, I cannot reproduce the issue.
For anyone able to use iText 7.1.1 or newer, I expect the solution by mkl to be better. If you are forced to use iText 7.0.5 like I was, the following worked for my reference PDF:
private static boolean hasJavascript(PdfDocument pdfDoc, String theFile) {
int n = pdfDoc.getNumberOfPages();
for (int i = 1; i <= n; i++) {
PdfPage pdfPage = pdfDoc.getPage(i);
List<PdfAnnotation> annotList = pdfPage.getAnnotations();
if (ListUtility.hasData(annotList)) {
for (PdfAnnotation annot : annotList) {
if (annot.getSubtype().equals(PdfName.Link)) {
continue;
}
PdfDictionary annotationAction = annot.getPdfObject().getAsDictionary(PdfName.A);
if (annotationAction != null && PdfName.JavaScript.equals(annotationAction.get(PdfName.S))) {
PdfString javascript = annotationAction.getAsString(PdfName.JS);
if (StringUtility.hasData(javascript.getValue())) {
log.debug("JavaScript found in PDF on page " + i);
log.trace(javascript.getValue());
return true;
}
}
}
}
}
String javaScriptInPdf = getJavaScriptFromPdfDocument(pdfDoc);
if (StringUtility.hasData(javaScriptInPdf)) {
log.debug("JavaScript found using iText 7");
log.trace(javaScriptInPdf);
return true;
}
log.debug("JavaScript not found in PDF");
return false;
}
//
private static String getJavaScriptFromPdfDocument(PdfDocument pdfDoc) {
StringBuilder strBuf = new StringBuilder();
try {
PdfDictionary pdfDictionaryCatalog = pdfDoc.getCatalog().getPdfObject();
if (pdfDictionaryCatalog == null) {
log.trace("getJavaScriptFromPdfDocument(): pdfDictionaryCatalog null; return null");
return null;
}
PdfDictionary pdfDictionaryNames = pdfDictionaryCatalog.getAsDictionary(PdfName.Names);
if (pdfDictionaryNames == null) {
log.trace("getJavaScriptFromPdfDocument(): PdfDictionary for PdfName.Names null; return null");
return null;
}
PdfDictionary pdfDictionaryJavaScript = pdfDictionaryNames.getAsDictionary(PdfName.JavaScript);
if (pdfDictionaryJavaScript == null) {
log.trace("getJavaScriptFromPdfDocument(): PdfDictionary for PdfName.JavaScript null; return null");
return null;
}
Set<Entry<PdfName, PdfObject>> set = pdfDictionaryJavaScript.entrySet();
for (Entry<PdfName, PdfObject> pdfObjectEntry : set) {
PdfObject pdfObj = pdfObjectEntry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
} else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && pdfObjectEntry.getKey().getValue().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
}
catch (Exception e) {
log.debug(e,e);
}
return strBuf.toString();
}
//
private static void getJavaScriptFromPdfArray(PdfArray pdfArray, StringBuilder strBuf) {
if (pdfArray == null) {
return;
}
for (PdfObject pdfObj : pdfArray) {
// To get same output as getJavaScriptUsingiText559(), not appending String values found in array to strBuf
if (pdfObj == null) {
continue;
}
else if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}
else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
}
}
}
//
private static void getJavaScriptFromPdfDictionary(PdfDictionary pdfDict, StringBuilder strBuf) {
if (pdfDict == null) {
return;
}
PdfObject pdfObj = pdfDict.get(PdfName.JS);
if (pdfObj == null) {
return;
}
if (pdfObj.isString()) {
strBuf.append(((PdfString) pdfObj).getValue());
}
else if (pdfObj.isStream()) {
strBuf.append(getStringFromPdfStream((PdfStream) pdfObj, TRUNCATE_PDF_STREAM_AT));
}
else if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary) pdfObj, strBuf);
}
else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
}
}
I know this is a very old thread, still sharing my code to add couple of things, on top of what mkl and James wrote.
// iText V 7.0.2
//To get javascript that is added through OpenAction
PdfDocument srcPdf = new PdfDocument(new PdfReader(srcFilePath));
PdfDictionary pdfDictionaryCatalog = srcPdf.getCatalog().getPdfObject();
PdfDictionary namesDictionary = pdfDictionaryCatalog.getAsDictionary(PdfName.OpenAction);
if(namesDictionary != null) {
PdfObject pdfObj = namesDictionary.get(PdfName.JS);
if(pdfObj != null) {
StringBuilder strBuf = new StringBuilder();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString()) {
strBuf.append(((PdfString) pdfObj).getValue());
}
System.out.println("*****OPENACTION****** "+strBuf.toString());
}
}
// To get java script available from NAMES dictionary
namesDictionary = pdfDictionaryCatalog.getAsDictionary(PdfName.Names);
if(namesDictionary != null) {
PdfDictionary javascriptDictionary = namesDictionary.getAsDictionary(PdfName.JavaScript);
if(javascriptDictionary != null) {
StringBuilder strBuf = new StringBuilder();
Set<Entry<PdfName, PdfObject>> set = javascriptDictionary.entrySet();
for (Entry<PdfName, PdfObject> entry : set) {
PdfObject pdfObj = entry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && entry.getKey().getValue().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
System.out.println("*****JAVASCRIPT****** "+strBuf.toString());
}
}
// To get java script from name tree JAVASCRIPT
PdfNameTree nameTree = srcPdf.getCatalog().getNameTree(PdfName.JavaScript);
if(nameTree != null) {
Map<String, PdfObject> objs = nameTree.getNames();
if(objs != null) {
StringBuilder strBuf = new StringBuilder();
for (Entry<String, PdfObject> entry : objs.entrySet()) {
PdfObject pdfObj = entry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && entry.getKey().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
System.out.println("*****JAVASCRIPT NAMED TREE****** "+strBuf.toString());
}
}
// To get java script at the annotation action level
for (int i = 1; i <= srcPdf.getNumberOfPages(); i++) {
PdfPage page = srcPdf.getPage(i);
List<PdfAnnotation> annotList = page.getAnnotations();
if(annotList != null) {
for (PdfAnnotation pdfAnnotation : annotList) {
if(pdfAnnotation.getPdfObject() != null) {
PdfDictionary annotationAction = pdfAnnotation.getPdfObject().getAsDictionary(PdfName.A);
if (annotationAction != null && PdfName.JavaScript.equals(annotationAction.get(PdfName.S))) {
PdfString javascript = annotationAction.getAsString(PdfName.JS);
if(javascript != null) {
System.out.println("ANNOTATION "+javascript);
}
}
}
}
}
}
/*getJavaScriptFromPdfDictionary() and getJavaScriptFromPdfArray() methods are the same from James answer. */

Liferay - Select item filled with json responseData

It's my first post on stackoverflow so I hope I won't make too many mistakes.
I've a problem with filling Java List and sending it to aui:select as options. My goal is to fill aui:select dynamically whenever one of their options is changed. For example: if you change first select item (county), second and third items (community and city respectively) are emptied and then filled with data dependent on selected county.
I've come to a conclusion that whenever there's a "mvcPath" parameter in Query String Parameters this code basically copies code from the whole page. This code works well whenever there's no "mvcPath" though. Sadly, I need this parameter to change pages (from search results to selected result details).
Image showing badly filled select item
Image showing correctly filled select item
Java code:
#Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId != 0) {
System.out.println("County id: " + countySelectedId);
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId == 0) {
System.out.println("No county chosen.");
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId != 0) {
System.out.println("Community id: " + communitySelectedId);
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId == 0) {
System.out.println("No community chosen.");
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = resourceResponse.getWriter();
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}
Script:
<aui:script>
AUI().use('aui-base', 'aui-io-request', 'aui-node',
function(A) {A.one("#<portlet:namespace />countySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />countyDictionaryId" : A.one("#<portlet:namespace />countySelect").val(),
'<portlet:namespace />countySelected' : 'countySelected'
},
dataType : 'json',
on : {
success : function() {
var communitiesList = this.get('responseData');
A.one('#<portlet:namespace />communitySelect').empty();
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />communitySelect').prepend("<option value='0'> </option>");
for (var i in communitiesList) {
console.info(communitiesList[i]);
A.one('#<portlet:namespace />communitySelect').append("<option value='" + communitiesList[i].communityDictionaryId + "'>" + communitiesList[i].communityName + "</option>");
}
}
}
});
});
A.one("#<portlet:namespace />communitySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />communityDictionaryId" : A.one("#<portlet:namespace />communitySelect").val(),
'<portlet:namespace />communitySelected' : 'communitySelected'
},
dataType : 'json',
on : {
success : function() {
var citiesList = this.get('responseData');
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />citySelect').prepend("<option value='0'> </option>");
for (var i in citiesList) {
console.info(citiesList[i]);
A.one('#<portlet:namespace />citySelect').append("<option value='" + citiesList[i].cityDictionaryId + "'>" + citiesList[i].cityName + "</option>");
}
}
}
});
});
});
After some changes in server-side code I managed to fix this issue. I'm not really sure how did as small changes as those helped but I'm happy to close this thread.
This is the server-side code:
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected")) {
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
if (countySelectedId == 0) {
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} else {
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected")) {
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
if (communitySelectedId == 0) {
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} else {
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = new PrintWriter(resourceResponse.getPortletOutputStream());
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}

#Controller returns empty page with "ok"

I'm trying to save a file with js from modal window. I save it all right but then I'm redirected to the page with only "ok" written on it.
I mean this:
My js looks like:
var name = $('#upload-track-name').val();
var description = $('#upload-track-description').val();
var file = document.getElementById('input-file').files[0];
var isValidate = true;
if (name.trim() == '') {
$('#error-upload-track-name').show();
isValidate = false;
}
if (!file) {
$('#error-upload-track-file').show();
isValidate = false;
}
if (!isValidate) {
return;
}
$.ajax({
url: '/tracks/upload',//I see this empty page on this url
type: 'post',
data: {
file: file,
name: name,
description: description
},
success: function (data){
if (data == 1) {
$('#error-upload-track-file').hide();
$('#error-upload-track-name').show();
} else if (data == 2) {
$('#error-upload-track-name').hide();
$('#error-upload-track-file').show();
} else {
$('#modal-upload-success').show();
}
})
And here is my #Controller:
#ResponseBody
#RequestMapping(value = TracksGeopointsRoutes.UPLOAD, method = RequestMethod.POST)
public String uploadTrack(#RequestParam MultipartFile file,
#RequestParam String name,
#RequestParam(required = false, defaultValue = "") String description,
Model model){
TracksGeopointsDoc tracksGeopointsDoc = new TracksGeopointsDoc();
if (name.equals("")) {
return "1";
}
if (file.getSize() == 0 || file == null){
return "2";
}
ObjectId fileId = fileService.saveWithDelete(file, null);
tracksGeopointsDoc.setFile(fileId);
tracksGeopointsDoc.setUploadDate(new Date());
tracksGeopointsDoc.setName(name);
tracksGeopointsDoc.setDescription(description);
tracksGeopointsService.saveTrack(tracksGeopointsDoc);
try {
File convFile = tracksGeopointsService.convert(file);
String s = convFile.getAbsolutePath();
mySaxParser.setUpMySaxParser(convFile.getAbsolutePath(), tracksGeopointsDoc.getId(), convFile.getName());
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
I suspect that it is because of #ResponseBody annotation. And if I am right can anyone tell me how can I avoid this.

Ajax method doesn't fire controller Action method

Javascript/Jquery:
specialInsDialog.dialog('open');
specialInsDialog.find('#buttonSave').live('click', function () {
function addSpecialInstuction(spinstructionVal, isYesVal) {
$.ajax({
type: "POST",
url: "/Portal/AddSpecialInstuction",
dataType: 'json',
data: { providerKey: selProviderKey, ownerKey: selOwnerKey, petKey: selPetKey, instruction: spinstructionVal, isPermenant: isYesVal, invoiceId: selInvoiceId },
success: function (data) {
alert('sam');
}
});
}
var chkBox = document.getElementById('checkboxSpecialIns');
if (chkBox.checked) {
var oTable = document.getElementById('table');
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
var isYes = oCells[1].childNodes[0].checked;
var spinstruction = oCells[2].childNodes[0].value;
if (typeof (spinstruction) != 'undefined' && spinstruction != '') {
addSpecialInstuction(spinstruction, isYes);
}
}
}
});
Controller :
[HttpPost]
public JsonResult AddSpecialInstuction(string providerKey, string ownerKey, string petKey, string instruction, bool isPermenant, string invoiceId)
{
char[] delimiter = {'+'};
string[] petKeys = petKey.Split(delimiter);
Pet pet = null;
foreach (var key in petKeys)
{
pet = BasicRepository.GetPet(ownerKey, key);
if (pet.SpecialInstructions != null && pet.SpecialInstructions.Where(a => a.Instruction.Trim() == instruction.Trim()).Count() <= 0)
{
pet.AddSpecialInstruction(new SpecialInstruction()
{
Instruction = instruction,
IsPermenant = isPermenant,
PetId = pet.Id,
InvoiceId = isPermenant ? Guid.Empty : Guid.Parse(invoiceId)
});
BasicRepository.Save();
}
}
Confirm("Your Special Instruction has been added.");
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}
I am having above kind of code and addSpecialInstuction method only fires when I do run the code by using firebug.Without firebug controller Action method doesn't fire.
Note: Above ajax method is inside the jquery UI popup
So Why is that ?

Categories