passing parameter to server in ExtJs - servlets

I am new in ExtJs.
I want to pass the value in my textbox to the server(Servlet) when I click on to the button. But as I am new to it I don't kn how to do it.
Please someone help me into this or suggest me some tutorial or example for this

Ext.Ajax.request can help you.
Code will be look like this:
new Ext.Button({
text: "Send to server",
handler: function () {
Ext.Ajax.request({
url: 'myPage.php',
success: function (){alert('Value has been sent!');},
failure: function (){alert('Failure of sending...');},
headers: {
'my-header': 'foo'
},
params: { foo: myTextField.getValue() }
});
}
})

in the url put your Servlet class name.
If you have a form with multiple buttons, for example Save, Update, Delete, you can to this :
// Your form fields ...
var buttonAdd = new Ext.Button({text:'Add', handler:addFunction});
var deleteAdd = new Ext.Button({text:'Delete', handler:deleteFunction});
function addFunction(){
Ext.Ajax.Request({
url: 'MyServlet', // you can fix a parameter like this : MyServlet?action=add
method: 'POST',
params: {
myField1: myField1.getValue()
// all your params....
}
success: function (result, request){
alert('Succesfully added ' + result.responseText);
},
failure: function (result, request){
alert('Error in server' + result.responseText);
}
});
function deleteFunction(){
Ext.Ajax.Request({
url: 'MyServlet', // you can fix a parameter like this : MyServlet?action=delete
method: 'POST',
params: {
myField1: myField1.getValue()
// all your params....
}
success: function (result, request){
alert('Succesfully added ' + result.responseText);
},
failure: function (result, request){
alert('Error in server' + result.responseText);
}
});
}
And in your Servlet, you can do this :
public void doPost(HttpServletRequest request, HttpServletResponse response){
String action = request.getParameter("action");
if(action.equals("add")){
// Your code for add method goes here
} else if(action.equals("delete")){
// Your code for delete method goes here
}
}

Related

Sending parameters of selected values to controller

I have html like this:
HTML
<div class="col-md-3 col-sm-12">
<div>
<p>Región</p>
<select id="lstRegion" class="form-control agenda_space" aria-hidden="true"></select>
</div>
<div>
<p>Solicitud</p>
<select id="lstSolicitud" class="form-control agenda_space" aria-hidden="true"> </select>
</div>
<br/>
<div>
Actualizar Filtro
<br/>
</div>
JS:
$("#lstRegion")
.getJSONCatalog({
onSuccess: function (response) {
console.log(response);
},
url: '/Agenda/GetRegion',
valueProperty: "ID",
textProperty: "valor"
});
//Load solicitud dropdown
$("#lstSolicitud")
.getJSONCatalog({
url: '/Agenda/GetSolicitud',
valueProperty: "ID",
textProperty: "solicitud"
});
Controller:
public ActionResult GetRegion()
{
try
{
var listaRegistros = db.CatalogoRegistros.Where(x => x.CatalogosCodigo == "REGI").Select(x => new
{
x.ID
,
valor = x.Valor
});
return Json(listaRegistros, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
public ActionResult GetSolicitud()
{
try
{
var listasolicitud = db.Solicitudes.Select(x => new { x.ID, solicitud = "Folio: " + x.ID });
return Json(listasolicitud, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
They work great I get my dropdwon lists very well, but now I want to do a GET action with selected values of each dropdown when my Actualizar Filtro it´s clicked.
But I´m really new in asp.net and I don´t know what I need to do to get selected values and send to controller.
As googling it I found I need to do method into my controller to get values so:
Controller will be:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
But I don´t know how to send them via JS, how can I do that to receive selected parameters into my controller? Regards
UPDATE
I try it using Ajax like:
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")',
data: { region: $('#lstRegion option:selected').html(), solicitud: $('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json',
success: function (data) {
console.log(data);
}});
But how can I trigger that function when event_add is clicked?
To run your updated ajax code on click, add #event_add click event handler and run your code inside it.
$('#event_add').click(function(e){
e.preventDefault(); //suppress default behavior
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")', // don't hard code your urls
data: { region: $('#lstRegion option:selected').html(), solicitud:
$('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json', // your returning a view, not json
success: function (data) {
console.log(data);
}});
});
Hi Try the below updated code:
$('#event_add').click(function(e){
var regionval = $('#lstRegion option:selected').html(),
var solicval = $('#lstSolicitud option:selected').html(),
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas", new { lstRegionValue = regionval, lstsolicitudValue =solicval})',
});
});
Note : I didnt test the code, but hope that it should work for you
Controller code:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
Hope it helps , thanks

AJAX data parse to Controller and return back

Here is an AJAX call to the controller:
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
alert(data);
$("#data").html(data);
},
error:{
}
});
In the controller code, I have a database query which returns multiple rows.
I want to return that variable back to JSON and print each row separately in AJAX and write that data in HTML.
Here is my Controller code
public ActionResult getChat()
{
var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
return Content(p.ToString());
}
The query is returning data. I am attaching an image that shows the variables content.
public JsonResult getChat()
{
var p = (from v in DB.chats
where v.chatuserID == id select new { v.status,
v.message
}).ToList();
return json(p,JsonRequestBehavior.AllowGet);
}
Now you can loop through the list in you ajax success callback function : here is stuff.
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
$.each(data,function(){
console.log("Status "+ data.status +" "+"Message"+ data.message);
});
},
error:{
}
});

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

jQuery Ajax success response returns HTML and not my intended value

I'm calling the Page Method and it's returning all of the HTML in this page and not the value of 1 or 0.
I don't know why this is. Can someone point me in the right direction ?
JavaScript:
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{}',
url: "main.aspx/IsInfoComplete",
success: function(data, textStatus, jqXHR) {
console.log(textStatus);
console.log(data.d);
// act on return value:
if(data==0) {
// todo -
} else if (data==1) {
// todo -
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
Server:
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
int returnValue = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetIsUserInfoComplete";
cmd.Parameters.AddWithValue("#UserName", userName);
conn.Open();
try
{
returnValue = (int)cmd.ExecuteScalar();
}
catch (Exception) { /* todo - */ }
}
return returnValue;
}
One thing you might try is to write your success function like this,
success: function (result) {
if (result!="False") {
//it worked
}
else {
//it failed
}
},
And change your server side method to return a bool. This would probably get you the desired results. I had to do this in something I wrote and it worked just fine. Little silly that you have to check for "False" but it worked.
Note: Case matters when looking for the word "False"
Look's like this is messing it up.. data here is an object and you are trying to compare the data with a 0 or a 1
success: function(data, textStatus, jqXHR) {
console.log(data); // Check the format of data in object
if(data != null){
console.log(data.d); // Generally your actual dat is in here
// act on return value:
if(data.d ==0) {
// todo -
} else if (data.d ==1) {
// todo -
}
}
},
If thats the case is your WebService returning a json object in the first place..
You need to decorate your webservice with this..
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
And set the dataType :'json' in your ajax request

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

Resources