calling servlet from button inside taskbar of grid extjs - javascript

I want to send textfield data to servlet after clicking button. Textfield and button in tbar of grid. I am using an Ajax request to call a servlet, but it is not calling it.
tbar: [{
xtype: 'textfield',
name: 'text'
}, {
text: 'Serach',
scope: this,
handler: function () {
Ext.Ajax.request({
method: 'GET',
loadMask: true,
scope: this,
url: 'http://localhost:8080/sampleweb/AccessServlet',
success: function (response, request) {
Ext.MessageBox.alert('success', response.responseText);
},
failure: function (response, request) {
Ext.MessageBox.alert('failure', response.responseText);
},
params: {
firstname: text.getValue()
}
});
}
}]

You do not need to put http://localhost:8080 in the AJAX request. Just put AccessServlet as the URL
or /sampleweb/AccessServlet
As others have suggested, what is in the net panel of your browser.
What do you see on the server console ?
You can enable debugging on the server to see the request come in.

Related

JQGrid wont reload update after Add/Remove/Delete

I have a JQGrid that updates via an ajax call to a web service.
It's all working fine, except from when I update the grid (and write it back to my database), the changes are not reflected in the grid.
I have read numurous posts with people reporting similar issues, but have tried on the suggestions to no avail.
loadonce is set to false, I reset my datatype to JSON and I have tried to destroy the grid before reloading it.
Here is my code thus far;
function LoadGrid2() {
//jgcontracts Grid
$.ajax({
type: "POST",
contentType: "application/json",
url: "../WebService1.asmx/getDataContacts",
dataType: "json",
success: function (data) {
data = data.d;
$("#jqcontacts").jqGrid({
datatype: "local",
colNames: ['Contact ID', 'Customer ID', 'First Name', 'Last Name', 'Email'],
colModel: [
{ name: 'contid', key: true, index: 'contid', width: 55, editable: true },
{
name: 'cust_name', index: 'cust_name', width: 80, align: "left", editable: true, edittype: "select",
editoptions: {
value: {}
}
},
{ name: 'first_name', index: 'first_name', width: 55, editable: true },
{ name: 'last_name', index: 'last_name', width: 55, editable: true },
{ name: 'email', index: 'email', width: 170, editable: true }
],
data: data,
caption: "Contacts",
viewrecords: true,
height: 200,
rowNum: 10,
pager: "#jqcontactsPager"
});
$('#jqcontacts').navGrid('#jqcontactsPager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
// options for the Edit Dialog
{
url: "../WebService1.asmx/modifyDataContacts",
editData: {},
editCaption: "The Edit Dialog",
beforeShowForm: function (form) {
$('#contid', form).attr("disabled", true);
},
reloadAfterSubmit: true,
recreateForm: true,
checkOnUpdate: true,
checkOnSubmit: true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
url: "../WebService1.asmx/addDataContacts",
addData: {},
editCaption: "The Add Dialog",
beforeShowForm: function (form) {
$('#contid', form).attr("disabled", true);
},
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
url: "../WebService1.asmx/deleteDataContacts",
delData: {},
delCaption: "The Delete Dialog",
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
},
error:
function (msg) {
alert(msg.status + " " + msg.statusText);
}
});
}
Here is my WebMethod
[WebMethod]
public object getDataContacts()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT [contid] ,cust.[cust_name] ,[first_name] ,[last_name] ,[email] FROM [Indigo].[dbo].[contacts] con LEFT JOIN [Indigo].[dbo].[customers] cust on con.custid = cust.custid";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
object obj = new JavaScriptSerializer().DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[0]));
return obj;
}
Any help greatly appreciated.
You do not need of this code.
afterSubmit: function () {
$("#jqcontacts").setGridParam({ datatype: 'json'}).trigger('reloadGrid');
return [true];
},
Like you do, you do two ajax calls. If you set editurl in grid parameters or url like you do the edited data is posted automatically to the server with ajax call instead that your datatype is local.
jqGrid looks for url(editurl) parameter and not for the datatype when posting edited data.
Remove the afterSubmit event and test. If the data is not saved you will need to see what you posted to the server and your server side code for saving data.
Guriddo jqGrid is server side independent javascript lib when we speak about saving, retrieving, sorting,... data from server side.
UPDATE
I see why is this caused.
Let me explain.
Question: How do you obtain your initial data?
Answer: You obtain your data with your own ajax call and then pass this data to a grid with datatype local.
Q: How do you update your data?
A: You update your data remotely to the server with separate call using a build in jqGrid functionality.
Problem: if data type is local and updating is server side the update does not reflect the local data in grid since reloading it, it reloads the current local data which is not affected from the update.
How to solve? You have more than one options.
Reconstruct your grid so that it obtain a data direct using the grid option url and jsonReader. Maybe you will need here to read the docs - i.e all your interactions with the data are server side.
In case you do not want to make server sorting, paging and etc. you can use the grid option loadonce to true with combination of url obtaining data from the servrer and jsonReader . In this case you will need to return all the data from the server (not in portion). If you do so then you can set datatype to json in beforeSubmit event so that when the grid reloads after update, then it will read the updated data from the server.
Do not change you current grid configuration, but in this case you will need to set the option reloadAfterSubmit to false in navigator and write additional for updating the local grid data.
I prefer you to use the option2.
I see that there is a small problem with the grid in this situationand we will try to fix it in the future release.

sending data using POST method in sencha extjs rest webservice

I wanna save a model by sending data using post method to my web server,
I wrote these codes and noticed that sencha is sending data using the GET method.
how can I send the data using POST method?
my model code:
Ext.define('MyApp.model.emp.Roles', {
extend: 'MyApp.model.Base',
fields: [
{
type: 'int',
name: 'id'
},
{
type: 'string',
name: 'title'
},
],
proxy: {
type: 'ajax',
url : 'http://myweb.test/json/fa/myweb/managerole.jsp',
idParam: 'id',
extraParams: {
'action':'btnSave_Click'
},
method:'POST',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
},
}
});
save calling code:
{
xtype: 'button',
text: 'ذخیره',
handler:function()
{
var user = Ext.create('MyApp.model.emp.Roles', {title: 'A Role From Sencha'});
user.set('title','hi');
user.set('id',-1);
user.save({
params: user.getData(),
callback: function (records, operation) {
Ext.Msg.alert('User Save', operation.getResponse().responseText);
},
methodName:'POST',
method:'POST',
});
}
}
If you are using model then you need to use only actionMethods.
actionMethods Mapping of action name to HTTP request method. In the basic AjaxProxy these are set to 'GET' for 'read' actions and 'POST' for 'create', 'update' and 'destroy' actions. Defaults to:
{
create: 'POST',
read: 'GET',
update: 'POST',
destroy: 'POST'
}
In this FIDDLE, I have created a demo using model and button. I hope this will help/guide your to achieve your requirement.
*NOTE I have used only local url. I don't have any live url. You can see in network request data is sending in url.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('MyModel', {
extend: 'Ext.data.Model',
fields: ['version', 'code', 'framework', 'frameworkVersion', 'fiddleid', 'inspector', 'session'],
proxy: {
type: 'ajax',
url: 'local', //I am providing local url in your case you can provide your rest webservice url
useDefaultXhrHeader: false,
actionMethods: {
create: 'POST', //When you want to save/create new record
read: 'GET', //When you want to get data from server side
update: 'PUT', //When you want to update the record
destroy: 'DELETE' //When you want to delete the record
},
paramAsJson: true // if You want to encode the data from clint side then it should be true otherwise false
}
});
Ext.create({
fullscreen: true,
renderTo: Ext.getBody(),
xtype: 'panel',
title: 'sending data using POST method in sencha extjs rest webservice',
padding: 10,
items: [{
xtype: 'button',
text: 'Send Data',
margin: 15,
style: {
background: '#ccc'
},
height: 50,
width: '100%',
handler: function () {
var MyModel = Ext.create('MyModel', {
version: "2",
code: '',
framework: "291",
frameworkVersion: "",
fiddleid: "",
inspector: "",
session: ''
});
MyModel.save({
success: function (records, operation) {
//When data will save on sever side then response will come in success
Ext.Msg.alert('User Save', 'Data saved');
},
failure: function (records, operation) {
//If some error occure on server side the reponse will come in failure function
Ext.Msg.alert(`Error ${operation.error.status}`, operation.error.statusText);
}
});
}
}]
});
}
});

Follow the ASP.NET ActionResult after Ajax call

A controller returns an ActionResult, i.e.:
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// do something
return RedirectToAction("Index", "Orders", null });
}
this works fine is I use an ActionLink in the view.
But the actual call is done via Ajax:
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
with the:
$("html").html(response);
line I'm trying to follow the returned html page.
It doesn't work: the html is rendered wrong (layout and colors are different) and even the address is not correct (of course it remains on the current page, instead to follow the Controller path).
I'm not sure if this is possible to do in jQuery.
Why I use an Ajax call instead of the ActionLink? Because I need to wait a confirm by the user:
$("#btnCancel").click(function () {
event.preventDefault();
swal({
title: "#Resources.MsgCancelOrderTitle",
text: "#Resources.MsgCancelOrderText",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "#Resources.MsgCancelOrderConfirm",
cancelButtonText: "#Resources.MsgCancelOrderCancel",
closeOnConfirm: false,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "#Resources.MsgCancelOrderSuccessTitle",
text: "#Resources.MsgCancelOrderSuccessText",
type: "success"
},
function () {
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
});
}
});
});
If you want to redirect to another view, then don't bother with ajax, it defeats the entire purpose of it. Generally an ajax call returns either some data (JSON or XML) or a small snippet of HTML which is designed to fit somewhere within the page which made the ajax call (generally implemented in MVC as a Partial View).
If you need the redirect, then do it like this:
Once the user confirms their choice via the alert box, then if the request needed uses the GET method (like your example) then simply a call to window.location.href with the appropriate URL will do it. If it was using POST, then normally there'd be a HTML form you could instruct to submit itself.

ExtJS GET action to store returns 500 in FireFox

I'm getting the strangest behavior from FireFox when loading data from a Web API GET request whereas other browsers do this perfectly. Here is what Fiddler can tell me when I use Firefox:
3817 500 HTTP localhost:52543 /api/Tasks/Get?_dc=1442848131483&page=1&start=0&limit=25 5 403 private application/xml; charset=utf-8 firefox:138020
Same action, other browser (Chrome):
3954 200 HTTP localhost:52543 /api/Tasks/Get?_dc=1442848159073&page=1&start=0&limit=25 1 508 no-cache; Expires: -1 application/json; charset=utf-8 chrome:2808
I'm unable to catch the error in the Application_Error, nor do I receive errors in the exception listener on the client-side, so I suspect something is going wrong between returning the result to the client and the client processing the results, but I have no clue at all where the problem might be situated.
Here is the store definition:
Ext.define('SchedulerApp.store.UnplannedTaskStore', {
extend: 'Ext.data.Store',
model: 'UnplannedTask',
autosync: false,
autoLoad: true,
proxy: {
type: 'rest',
api: {
read: '/api/Tasks/Get',
add: '/api/Tasks/Add',
update: '/api/Tasks/Update',
destroy: '/api/Tasks/Destroy'
},
actionMethods: {
create: 'POST',
read: 'GET',
update: 'POST',
destroy: 'POST'
},
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'total'
},
writer: {
type: 'json',
writeAllFields: true
}
},
listeners: {
load: function (sender, node, records) {
},
exception: function (proxy, response, options) {
Ext.MessageBox.alert('Error', response.status + ": " + response.statusText);
}
}
});
and the model:
Ext.define('UnplannedTask', {
extend: 'Ext.data.Model',
fields: [
{ name: 'Importance', type: 'float' },
{ name: 'Category', type: 'string' },
{ name: 'TaskNo', type: 'float' }
]
});
This is what I have in the Web API:
[System.Web.Http.HttpGet]
public async Task<dynamic> Get(string page, string start, string limit)
{
// Get items from database with request information from the Kendo Grid Control
PagingResult<TaskViewModel> tasks = await this.Worker.GetPagedTasksAsync(int.Parse(page), int.Parse(limit), null, null);
// Map them to store objects
var convertedTasks = new SchedulerTasksViewModel()
{
total = tasks.Count,
data = tasks.Items.Select(x => new SchedulerTask()
{
Importance = x.Importance,
Category = x.Category,
TaskNo = x.TaskNumber
}).ToArray()
};
var response = Request.CreateResponse(HttpStatusCode.OK, convertedTasks);
return response;
}
Could it be a browser issue or am I missing something on the server side?
Try adding this header to your proxy:
headers: {'Content-Type': "application/json" }
I would like to elaborate a bit. The error is thrown by the XML serializer; you don't see the details because IIS does not send them to the front.
I would recommend to modify all your API calls such that they work with XML as well - even if your front-end does not use XML. It's far easier to debug if you can just open API calls in new browser tabs and the XML serializer does not mask code errors with serialization errors.
To see the error message, you would have to allow your development IIS to bring errors to the front:
Open the IIS7 manager
Select the Website and on its features view, double click on “Error Pages”.
Right click and select the “Edit Feature Settings…” or select the same from the Actions pane (in the right hand side)
Select the “Detailed errors” radio button and click on OK
(Source)
My best guess is that you just have to decorate some types or properties with [DataContract], [DataContractAttribute] or [DataMemberAttribute]. The error message will tell you which ones and how to decorate.
Another thing entirely: If you use more than one Ajax request, I'd recommend to define an override on the Ajax proxy. That way you can't forget one:
Ext.define("MyApp.override.Ajax", {
override:'Ext.data.proxy.Ajax',
headers:{'Accept':'application/json'}
});

Call ajax call after facebook user send invite request

I want to know where should I put my ajax call when the user clicks the send request button on the fb ui invite. Currently, I put it after the fb ui syntax:
function sendRequest(gFriendID, gFriendName) {
FB.ui({
method: 'apprequests',
title: 'Check out LoyaltyNmore!',
to: gFriendID,
message: 'Hi ' + gFriendName + ' join me in earning loyalty points!',
}, fbCallback);
$.ajax({
type: "POST",
url: "/home/StoreInvite?userId=" + gFriendID,
success: function (data) {
},
error: function (err) {
}
})
}
}
But as expected. The ajax call gets executed when the app opens up the request UI. I want the ajax call to be executed right after the user clicks send request not when the request UI shows. Also when cancel is clicked. I don't want my ajax call to be executed. Any ideas? Thanks
You basically need to put your ajax call inside the facebook callback function... The response will contain details about to whom the app was shared. The 'to' array will get you the ids of those who were invited.
function sendRequest(gFriendID, gFriendName) {
FB.ui({
method: 'apprequests',
title: 'Check out LoyaltyNmore!',
to: gFriendID,
message: 'Hi ' + gFriendName + ' join me in earning loyalty points!',
}, function(response)
{
if(response.to.length)
{
$.ajax({
type: "POST",
url: "/home/StoreInvite?userId=" + gFriendID,
success: function (data) {
},
error: function (err) {
}
});
}
});
}

Categories