Cant call a servlet from ExtJs controller - javascript

i have a controller in extjs application, from where i have to call a servlet. But i am unable to call that servlet from controller here is my controller code .....
when i am running the application always failure part is showing "server-side failure with status code" this is the problem:
Ext.define('Gamma.controller.ControlFile', {
extend : 'Ext.app.Controller',
//define the stores
stores : ['BarColumn',
'RadarView',
'VoiceCallStore',
'SMSCallStore',
'MMSCallStore',
'GPRSUsageStore'],
//define the models
models : ['BarCol',
'radar',
'VoiceCallModel',
'SMSCallModel',
'MMSCallModel',
'GPRSUsageModel'],
//define the views
views : ['BarColumnChart',
'LineChart',
'RadarChart',
'VoicePie',
'SMSPie',
'MMSPie',
'GPRSPie'],
initializedEvents: false,
init: function() {
this.control({
'#barColumnChart': {
afterlayout: this.afterChartLayout
}
});
},
afterChartLayout: function(){
var me=this;
if(this.initializedEvents==true) return;
this.initializedEvents=true;
Ext.getCmp('barColumnChart').series.items[0].on('itemmousedown',function(obj){
// alert(obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count']);
var barData=obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count'];
me.dataBaseCall(obj.storeItem.data['source'],obj.storeItem.data['count']);
});
},
dataBaseCall: function(source,count){
//alert(barData);
Ext.Ajax.request({
url: "CallRatiosAnalysis",
success: function(response, opts){
//do what you want with the response here
console.log("hiiiiiiiiiiii");
},
failure: function(response, opts) {
alert("server-side failure with status code " + response.status);
},
params: {
source: source,
count: count
}
});
}
});
and this is my Servlet:
public class CallRatiosAnalysis extends HttpServlet {
public CallRatiosAnalysis() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String limit = request.getParameter("limit");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ArrayList<IndCallType> ratios = new ArrayList<IndCallType>();
ratios.add(new IndCallType("Voice", "40"));
ratios.add(new IndCallType("SMS", "30"));
ratios.add(new IndCallType("MMS", "5"));
ratios.add(new IndCallType("GPRS", "20"));
ratios.add(new IndCallType("Others", "5"));
Gson gson = new Gson();
JsonArray arrayObj = new JsonArray();
for (int i = 0; i < ratios.size(); i++) {
IndCallType count = ratios.get(i);
JsonElement linObj = gson.toJsonTree(count);
arrayObj.add(linObj);
}
JsonObject myObj = new JsonObject();
myObj.addProperty("success", true);
myObj.add("allCalls", arrayObj);
myObj.addProperty("allCallsRatio", ratios.size());
out.println(myObj.toString());
out.close();
}
}
This is the servlet where I have some dummy data and made json object to that data

Related

ajax post to MVC controller failed with 400 Bad Request

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() },

How to pass Dictionary from c#(server) to javascript(client)

I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX

Ajax response does not parse LocalDate

I need to pass Localdate as part of the Ajax response to jquery datatables. LocalDate field does not display its value. Instead it prints [object,Object]. Obviously, it means LocalDate was not deserialized. Can some one please explain how to deserialize Localdate to display it properly.
Below is my Jquery Code:
var table = $("#example").DataTable({
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : "jsonSource.web",
"aoColumns" : [
{
"mData" : "name"
}, {
"mData" : "position"
}, {
"mData" : "office"
}, {
"mData" : "phone"
}, {
"mData" : "salary"
}, {
"mData" : "dob"
}
],
columnDefs : [ {
targets : [ 5 ],
render : function(data, type, row) {
var json = JSON.stringify(data);
var date = JSON.parse(json);
console.log("json: " + json + "date : " + row);
return data;
}
}
} ]
});
Server Side code:
#RequestMapping(value = "/springPaginationDataTables.web", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody String springPaginationDataTables(HttpServletRequest request) throws IOException {
//Fetch search parameter
String searchParameter = request.getParameter("sSearch");
final String sortColumn = request.getParameter("iSortCol_0");
final String sortOrder = request.getParameter("sSortDir_0");
//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));
//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/pageDisplayLength)+1;
System.out.println("sSearch : "+searchParameter);
System.out.println("pageDisplayLength : "+pageDisplayLength);
System.out.println("pageNumber : "+pageNumber);
System.out.println("iSortCol_0 : "+sortColumn);
System.out.println("sSortDir_0 : "+sortOrder);
List<Person> personsList = new ArrayList<Person>();
Person person2 = new Person();
person2.setName("John Landy");
person2.setPosition("System Architect");
person2.setSalary("$320,800");
person2.setOffice("NY");
person2.setPhone("999999999");
person2.setStart_date("05/05/2010");
person2.setDob(LocalDate.parse("1989-07-09"));
personsList.add(person2);
//apply server side search
//apply server side sort
//BuildDataTable object
PersonJsonObject personJsonObject = new PersonJsonObject();
//Set Total display record
personJsonObject.setiTotalDisplayRecords(500);
//Set Total record
personJsonObject.setiTotalRecords(500);
personJsonObject.setAaData(personsList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(personJsonObject);
return json2;
}
I solved it. had to extend SimpleModule from codehaus to implement serialisation/deserialisation for LocalDate. Below is my code:
public class LocalDateSimpleModule extends SimpleModule{
public LocalDateSimpleModule(String name, Version version) {
super(name, version);
addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
#Override
public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
ToStringSerializer.instance.serialize(value, jgen, provider);
}
});
addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
#Override
public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
ToStringSerializer.instance.serialize(value, jgen, provider);
}
});
addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() {
#Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDate.parse(jp.getText());
}
});
addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
#Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDateTime.parse(jp.getText());
}
});
}
}
Register this module in servlet-springs.xml
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean name="localDateModule" class="packge.LocalDateSimpleModule">
<constructor-arg name="name" value="LocalDateModule" />
<constructor-arg name="version" ref="version" />
</bean>
<bean name ="version" class="org.codehaus.jackson.Version">
<constructor-arg value="1"/>//some value
<constructor-arg value="1"/>
<constructor-arg value="1"/>
<constructor-arg value=" "/>
</bean>

issue in display of html content stored in database in java

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.

How to get selected item from AUI autocomplete list

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

Categories

Resources