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

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.

Related

How to send an array/List with ajax and jquery. Failed to load resource: the server responded with a status of 415 ()

I am new with Jquery Ajax, I am trying to send an array via post. In the following way.
$(function(){
$("#btnSave").click(function(){
var datos = new Array();
$("#imgCurrent tr").each(function () {
var row = $(this);
var id =row.find("td:eq(0)").text();//.html();;
var data=
{
RepositoryCatalogueID: id
}
datos.push(data);
});
var url = "#Url.Action("EditPosition","Carrusel")";
$.ajax({
url: url,
type: 'POST',
contentType: 'json',
data: (datos),
success: function (data) {
$.alert({
icon: "~/Content/Images/success.png",
title: 'Restaurar Imagen',
content: 'Restauración exitosa.',
});
}
})
});
});
An object of this type is received in my controller.
public JsonResult EditPosition([FromBody] IEnumerable<CarruselViewModel> model)
{
bool success = false;
JsonResult jResult;
string message = string.Empty;}
It throws me the error Failed to load resource: the server responded with a status of 415()
And it never enters the controller
you need to cast your data to json. use this :
data: JSON.stringify(datos),
also make sure you put [HttpPost] attribute on top of your action method;
[HttpPost]
public JsonResult EditPosition([FromBody] IEnumerable<CarruselViewModel>
model)
{
bool success = false;
JsonResult jResult;
string message = string.Empty;
}

I've created an AJAX call to send data to a stored procedure. Why isn't it working?

I will post my code and I'm curious if anyone can see what I am doing wrong here. I've tested the Stored Procedure and that works fine so the break must be somewhere in the Controller or Model. See code below:
VIEW:
function saveCalc() {
var TotCost = $("#totCost").val();
var GPM = $("#CalcAmt").val();
var SP = parseFloat(TotCost / (1 - GPM));
var ID = parseInt($("#ID").val());
debugger;
$.ajax({
url: 'Items/ItemsReport_Update2',
type: "Get",
data: { ID: ID, SP: SP },
success: function () {
CalcDialog.close();
CalcDestroy();
$('#ItemsReportgrid').data('kendoGrid').dataSource.read();
$('#ItemsReportgrid').data('kendoGrid').refresh();
}
});
}
CONTROLLER:
public void ItemsReport_Update2( int ID, double SP)
{
ItemsModel oItemsModel = new ItemsModel();
oItemsModel.UpdateItemsReport2(ID, SP);
}
MODEL:
public void UpdateItemsReport2(int ID, double SP)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_UpdateInvItem2", con)
{
CommandType = CommandType.StoredProcedure
};
if (con.State == ConnectionState.Closed)
con.Open();
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#SP", SP);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
Thanks in advance for any help. I've run the script with a debugger and it is passing the data correctly.
url: '/Items/ItemsReport_Update2',
You missed '/' in ajax URL
I think your issue is that grid is not populating with the result data
Please change your controller like this if you are loading a kendo grid data
public void ItemsReport_Update2( [DataSourceRequest]DataSourceRequest request,int ID, double SP)
{
//Create a list with your model type
List<> lst = new List<>();
ItemsModel oItemsModel = new ItemsModel();
oItemsModel.UpdateItemsReport2(ID, SP);
DataSourceResult result = lst.ToDataSourceResult(request);
var jsonResult = Json(result,JsonRequestBehavior.AllowGet);
}
then you need to change the javascript like this
function saveCalc() {
var TotCost = $("#totCost").val();
var GPM = $("#CalcAmt").val();
var SP = parseFloat(TotCost / (1 - GPM));
var ID = parseInt($("#ID").val());
var grid = $("#ItemsReportgrid").data('kendoGrid');
debugger;
$.ajax({
url: '/Items/ItemsReport_Update2',
type: "Get",
data: { ID: ID, SP: SP },
success: function (result) {
grid.dataSource.data(result.Data);
CalcDialog.close();
CalcDestroy();
}
});
}

passing json to kendoui grid

I would really appreciate guidance.
My script will make a call to my server, grab some data and bring it back as JSON. Then I call ServiceSucceeded(msg); I pass in the JSON results in msg. Now in ServiceSucceeded I want to display my results on kendoui grid. That is the part that I can't get to work. It gives no browser errors.
This code might be awful, so please school me on this , thanks!
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.common.min.css" />
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.default.min.css" />
<script src="../../assets/telerik/js/jquery.min.js"></script>
<script src="../../assets/telerik/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid">
</div>
<div>
<script>
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var Username;
var Password;
var qryVar;
var locationName;
function GetAllReportDB() {
var dataId = "1";
Type = "GET";
qryVar = "userName=Simon"
Url = "http://localhost/UserReportMap.svc/GetAllReportDB?" + qryVar;
Data = '{"Contains": "Kir","DBName":"Bony","Operator":"BON0D"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; ProcessData = true;
Username = "test";
Password = "test";
CallService();
}
function CallService() {
$.support.cors = true;
$.ajax({
cache: false,
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
beforeSend: function (xhr2) {
xhr2.setRequestHeader("Authorization", "Basic " + window.btoa(Username + ':' + Password));
},
success: function (msg) {
ServiceSucceeded(msg);
alert("Succeeded");
},
error: function (errMsg) {
alert("Fail!");
}
});
}
function ServiceSucceeded(msg) {
var myResults = { "d": [{msg}] };
alert(JSON.stringify(msg));
$(function () {
$("#grid").kendoGrid({
dataType: "json",
schem: {
data: "d"
}
//columns: [{ title: "First Name" },
// { title: "Last Name" }]
});
});
}
$(document).ready(
function () {
GetAllReportDB();
}
);
</script>
</div>
</body>
</html>
Well, you have one typo at schem. It should be schema and not schem.
Anyway, I recommend check API docs, there is written what you need.
And to your question:
You are missing dataSource in your grid so it doesn't know from what data grid should be rendered.
$("#grid").kendoGrid({
dataSource: {
type: "json",
data: jsonData,
pageSize: 20
},
...
});
So line var myResults = { "d": [{msg}] }; can be removed and msg data can be assigned into dataSource. Then you will be able to set columns - here demo
And also consider, if you need load your json data in function and result assign into variable. Grid is able to load data from server without that - server just has to return json data, like in this example

Calling a function in json from a jqgrid custom button

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!

MVC3 return JSON on error instead of HTML [duplicate]

How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
and to register a global error handler you could use the $.ajaxSetup() method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
and finally invoke it:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '#Html.Raw(#Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.
To set a default globally, you can use the function described here:
http://api.jquery.com/jQuery.ajaxSetup.