Calling a function in json from a jqgrid custom button - json

I have a jqgrid with some data. When two of the rows are selected, I'd like to add a record in the database (in a different table than the one of the jqgrid). What I do is to create a new button in the navigation bar with the following code:
jQuery("#tabla").navButtonAdd('#navegacion',
{
caption: "Crear tramo", buttonicon: "ui-icon-extlink", cursor:"pointer", title: "Crear tramo",
onClickButton: $(function() {
var selectedrows = $("#tabla").jqGrid('getGridParam','selarrrow');
var er1=$("#tabla").jqGrid('getRowData',selectedrows[0]);
var er2=$("#tabla").jqGrid('getRowData',selectedrows[1]);
$.ajax({
dataType: 'json',
mtype: 'POST',
url: 'json/operaciones.jsp',
postData: { oper:'add', id1:er1, id2:er2},
success: function(data) {
alert(data);
}
})
})
});
And what I have in the file operaciones.jsp is:
<%
String salida="";
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("my", "Connection", "Parameters");
try {
System.out.println("Parámetros enviados:");
Enumeration e=request.getParameterNames();
while (e.hasMoreElements()){
String par=(String)e.nextElement();
System.out.println(par+":"+request.getParameter(par));
}
String operacion=request.getParameter("oper");
String id1=request.getParameter("id2");
String id2=request.getParameter("id2");
String comentarios="prueba";
if (operacion.equals("add")) {
PreparedStatement stmt=con.prepareStatement(
"INSERT INTO TRAMOS "+
"(COMENTARIOS,ELEMENTOS_REGISTROCODIGO,ELEMENTOS_REGISTROCODIGO2, ENTIDADESCIF) "+
"VALUES (?,?,?,?,?)");
stmt.setString(1,comentarios);
stmt.setString(2,id1);
stmt.setString(3,id2);
stmt.setString(4,"Q1818002F");
stmt.executeUpdate();
stmt.close();
salida="{\"correcto\":true,\"clave\":\""+id1+"|"+id2+"\",\"mensaje\":\"OK\"}";
}
}
catch (Exception e) {
String cadenaError=e.toString().substring(e.toString().indexOf(":")+2);
cadenaError=cadenaError.replace('\n',' ');
cadenaError=cadenaError.replace("\"","\\\"");
salida="{\"correcto\":false,\"clave\":\"\",\"mensaje\":\""+e.toString()+"\"}";
}
finally {
con.close();
}
System.out.println("salida:"+salida);
response.setContentType("application/json");
%>
<%=salida%>
But it's not working, what I get is "java.lang.NullPointerException". Where is the mistake? How can I send the data to the file operaciones.jsp?
Thanks in advanced,
Natalia

One clear error in the code which you use is the usage of postData instead of data and mtype instead of type as parameters of jQuery.ajax.
I recommend you additionally to write more safe code. For example you use selectedrows[0] and selectedrows[1] inside of the onClickButton before verifying that selectedrows is not null and that selectedrows.length > 1. If the user click for example on the button before at least two lines are selected one get exception in JavaScript code.

It was a stupid error... What finally worked:
jQuery("#tabla").navButtonAdd('#navegacion',
{
caption: "Crear tramo", buttonicon: "ui-icon-extlink", cursor:"pointer", title: "Crear tramo",
onClickButton: function() {
selectedrows = $("#tabla").jqGrid('getGridParam','selarrrow');
if(selectedrows.length==2){
er1=$("#tabla").jqGrid('getRowData',selectedrows[0]);
er2=$("#tabla").jqGrid('getRowData',selectedrows[1]);
$.ajax({
datatype:'json',
type:'GET',
url:'json/operacionesTramos.jsp',
data:{oper:'add',id1:er1.codigo,id2:er2.codigo},
success: function(data) {
alert("Tramo creado");
}
})
}
else{
alert("Seleccione dos arquetas, por favor");
}
}
});
Thanks Oleg!

Related

Auto complete ERROR 404 in HTML (using ASP.NET and JQuery)

For some reason in asp.net project, my autocomplete won't work, I have tried different methods from using Data source in data connection but to no avail. I have already created a database for it called Diagnose but for some reason, it displays error 404 on jquery.
Here is my HTML code:
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#search-diagnosis").autocomplete({
source: function (request, response) {
var param = {
searchdetails: $('#search-diagnosis').val()
};
$.ajax({
url: "SearchController.cs/GetSearch",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return { value: item } }))
},
});
},
minLength: 1
});
});
</script>
<div class="search">
<input id="search-diagnosis" class="w-75" type="text" placeholder="Start typing your diagnois...">
</div>
Here is CS code:
[WebMethod]
public static List<string> GetSearch(string searchdetails)
{
List<string> search = new List<string>();
string mainconn = ConfigurationManager.ConnectionStrings["mybase.database"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = string.Format("select Name from [dbo].[Diagnose] where Name LIKE '%{0}%'", searchdetails);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
SqlDataReader sdr = sqlcomm.ExecuteReader();
while (sdr.Read())
{
search.Add(sdr.GetString(0));
}
sqlconn.Close();
return search;
}
It displays error:
When I open the jquery-1.8.0.js:8214 it shows me this xhr.send( ( s.hasContent && s.data ) || null );
I'm stuck at this problem for a while so any help would be great, thanks in advance :D <3
It is returning 404 not found. I think that GetSearch should be inside of an aspx or an ascx file. Webmethod works in System.Web context and in some point it will require Page.

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

Post list of string null on web api controller

In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

Retrieving search data from database using jQuery autocomplete?

I am using jQuery UI Autocomplete plugin for better data input in my ASP.NET web application.
http://jqueryui.com/demos/autocomplete/
However, I think I have somehow lost in this plugin.
I would like to ask what I should do in order to use this autocomplete function with the data retrieve from database?
I expect Ajax should be used for the real-time search,
but I have no idea how it can be done after looking at the demo in the website above.
Thanks so much.
Update:
Here is the code I have tried, doesn't work, but no error in firebug too.
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup?firstName=",
type: "POST",
data: {
"firstName": $('#FirstName').val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});
You need to create an action that does the lookup and returns the result as a JsonResult
e.g.
public ActionResult FirstNameLookup(string firstName)
{
var contacts = FindContacts(firstname);
return Json(contacts.ToArray(), JsonRequestBehavior.AllowGet);
}
I'm not sure if this will solve all your problems but here are a couple of edits you can make.
you don't need the "?firstname=" part of the url since you are using the data parameter for you ajax request.
rather than grabbing your search term with $('#FirstName').val(), try using the term property of the request object (request.term).
for example:
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup",
type: "POST",
data: {
"firstName": request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});