Need Help Diagnosing This Ajax Request Call - javascript

Need Help Diagnosing This Ajax Request Call.
filtered text is a text box from an input box further up the page , with filters is a Boolean checking if the user wants to search for anything at all and filtered text is what the user would like to filter by.
function GetData(torf) {
var watever = { "withfilters": torf, "filteredtext": $('#SortOrdersBy2').val() };
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
data: JSON.stringify(watever),
contentType: "application/json; charset=utf-8",
success: function (data) {
var employeeTable = $('#datatable tbody');
var employees = data;
for (i = 0; i < employees.length; i++) {
employeeTable.append('<tr><td>' + employees[i].CustomerId + '</td><td>' + employees[i].CustomerName + '</td><td>' + employees[i].Engineer + '</td></tr>');
}
},
error: function (err) {
alert("ERROR");
}
});
}
It Goes to this web service code and runs through it on load but still displays the error function.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
{
string connectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
List<Data1> Data = new List<Data1>();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand query = new SqlCommand
(withfilters ? "SELECT * FROM MainTable CustomerId LIKE '%" + (filteredtext) + "%' OR CustomerName LIKE '%" + (filteredtext) + "%' OR Engineer LIKE '%" + (filteredtext) + "%')"
: "SELECT * FROM MainTable",con);
SqlDataReader rdr = query.ExecuteReader();
while (rdr.Read())
{
Data1 data = new Data1();
data.CustomerId = Convert.ToInt32(rdr["CustomerId"]);
data.CustomerName = rdr["CustomerName"].ToString();
data.Engineer = rdr["Engineer"].ToString();
Data.Add(data);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(Data);
}
Any Help Would be greatly Appreciated, need more info let me know.

In your webservice you have set the UseHttpGet=true which means that this method can be executed using Http GET request not POST
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
However, in javascript you are trying to execute the method using POST from client-side
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
SOLUTION:
Remove the HttpGet=true from ScriptMethod attribute:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)

Related

Bind GridView With Database In MVC 5 In C# and i have ajax JavaScript

I have problem with create grid (without kendo)
I try to make a dictionary. I have a list of word and pass this to ajax JavaScript and show it to grid in view. but I don't know how to work with this :(.
thanks all
this is my controller
public ActionResult ChekingInBank(string username, string password, string datasource, string bnkname, string SqlQuery)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.InitialCatalog = bnkname;
builder.Password = password;
builder.UserID = username;
List<TranslateViewModel> translateViewList = new List< TranslateViewModel>();
WebGrid TranslateGrid = new WebGrid();
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(SqlQuery, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
TranslateViewModel translateView = new TranslateViewModel();
translateView.id = dr[0].ToString();
translateView.word = dr[1].ToString();
translateView.translate = dr[2].ToString();
translateViewList.Add(translateView);
}
if (translateViewList.Count>0)
{
return Json( new {translateViewList = translateViewList, JsonRequestBehavior.AllowGet);
}
else
{
return Json("No Record Found");
}
}
}
}
}
JavaScript
function chekingInBank() {
var translate = $("#eWord").val();
var bnkname = $("#combo").val();
var username = $("#Username").val().trim();
var password = $("#password").val();
var datasource = $("#Datasource").val();
var SqlQuery = "select * from lego.LocalizationView where Word =N'" + translate + "'";
if (bnkname) {
$.ajax({
url: 'Home/chekingInBank?' + "Username=" + username + "&Password=" + password + "&databaseConString=" + datasource + "&bnkname=" + bnkname,
data: {
bnkname: bnkname,
username: username,
password: password,
datasource: datasource,
SqlQuery: SqlQuery
},
//dataType: "json",
type: "get",
datatype: "json",
traditional: true,
success: function (data)
{
`I have problem with this `
debugger;
if (data != "No Record Found") {
$('#gridContent').html(data);
}
else {
alert('No Record Found')
}
},
});
}
else
{
//do nothing
}
}
and my view
and this :(((
#{
var grid = new WebGrid(VeiwModeList, canPage: true, rowsPerPage: 5,
selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.All);
}
#grid.GetHtml(
tableStyle: "webGrid",
columns: new[]
{
grid.Column("id"),
grid.Column("Word"),
grid.Column("Translate")
});
First of all, you should never send such data like database's username, password, database name and SQL query from javascript to server. This is dangerous because anyone gain access to your database. For example one can change your query to something like
var SqlQuery = "TRUNCATE TABLE lego.LocalizationView"
and your server code will execute this destructive query.
Next, I think you have some misunderstanding with using WebGrid. For example, your controller's method returns JSON, but in js code you put this JSON as html into HTML element:
$('#gridContent').html(data);
Also you didn't mention whether your controller action is decorated with HttpGet attribute.
I advise you to find and implement (reproduce) a working example of using WebGrid with AJAX requests, for example what I've googled: link
In this example Entity Framework is used to connect to data, but you can begin with returning static JSON in your controller method, to verify this all works altogether:
[HttpPost]
public JsonResult AjaxMethod(int pageIndex)
{
CustomerModel model = new CustomerModel();
model.PageIndex = pageIndex;
model.PageSize = 10;
model.RecordCount = 2; //number of records - for pager
int startIndex = (pageIndex - 1) * model.PageSize;
model.Customers = new List<Customer> //some random static data
{
new Customer
{
CustomerID = "AAAA",
City = "City 1",
ContactName = "Contact Name 1",
Country = "Country 1"
},
new Customer
{
CustomerID = "BBBB",
City = "City 2",
ContactName = "Contact Name 2",
Country = "Country 2"
}//, add some more dummy customer's info
};
return Json(model);
}
And when you'll reproduce it you can change the CustomerModel to your class, change POST to GET, connect to your database, modify grid columns and so on.

Call Webmethod to Fill DropDownList

I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}
Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.

Can i send string instead of json to MVC controller from ajax post?

I am coming across an issue trying to send long strings of JSON to a MVC controller. First let me explain the need, then I will explain what I have tried. I am preserving the HTML of the UI for a table into SQL. That way I can pull it back out and render it later. That being said, when I try to send from AJAX post to the controller, I keep getting the error that JSON max length has been hit.
What have I tried?
I have tried changing all settings in the web config and in the JSON serializer in the MVC controller to the int.MaxLength values. I have also changed my controller result to a content results instead of JsonResult. Here is some of the current code I use (stripped all unnecessary code and left what is needed for troubleshooting).
Controller:
[HttpPost]
[ValidateInput(false)]
/// <summary>
/// Inserts / updates a new saved quote template
/// </summary>
/// <param name="jsonData"></param>
public ActionResult SaveQuoteTemplate(string htmlTemplate, int totalRecords, int totalBadRecords, string templateName, string templateDescription, string templateNotes, string templateId)
{
var serializer = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
var returnData = new
{
StatusCodeEntity = ReturnCodeHandler.Status400,
StatusMessage = "Unkown error occurred while trying to save the template.",
};
var resultSet = new ContentResult
{
Content = serializer.Serialize(returnData),
ContentType = "application/json"
};
try
{
JsonModel<QuoteEntitySavedItemVM> jsonModel = new JsonModel<QuoteEntitySavedItemVM>();
if (!String.IsNullOrEmpty(htmlTemplate))
{
string userPrefix = Session["LoginID"] != null ? Session["LoginID"].ToString() : string.Empty;
QuoteEntitySavedItemVM qsvm = new QuoteEntitySavedItemVM()
{
JSON = htmlTemplate,
CreationDate = DateTime.Now,
Description = templateNotes,
TotalRecords = totalRecords,
TotalBadRecords = totalBadRecords,
Name = String.Format("{0} - {1}", userPrefix, templateName),
Id = QPortal.Web.Helpers.Utilities.SafeToInt32(templateId) //convert to int or safely returns 0 if null
};
qsvm.Id = _quoteEntityService.SavedQuoteTemplate(qsvm); //returns project id. So will now assign new on or same if update ran
if (qsvm.Id == -1)
{
var badReturn = new
{
StatusCodeEntity = ReturnCodeHandler.Status400,
StatusMessage = "There is already a project with this name. Please change name.",
ObjData = new List<QuoteEntitySavedItemVM>() { qsvm }
};
resultSet = new ContentResult
{
Content = serializer.Serialize(badReturn),
ContentType = "application/json"
};
}
else
{
var goodReturn = new
{
StatusCodeEntity = ReturnCodeHandler.Status200,
StatusMessage = "Project saved #" + DateTime.Now.ToString() + ".",
ObjData = new List<QuoteEntitySavedItemVM>() { qsvm }
};
resultSet = new ContentResult
{
Content = serializer.Serialize(goodReturn),
ContentType = "application/json"
};
}
}
else
{
var errorReturn = new
{
StatusCodeEntity = ReturnCodeHandler.Status400,
StatusMessage = "Saving project failed due to submitted quote model to save being null. Please verify that you currently have a network connection or refresh page and try again."
};
resultSet = new ContentResult
{
Content = serializer.Serialize(errorReturn),
ContentType = "application/json"
};
}
}
catch (Exception e)
{
var errorReturn = new
{
StatusCodeEntity = ReturnCodeHandler.Status500,
StatusMessage = "An unknown error occurred while trying to save project. Please refresh page and try again. Details: " + e.Message
};
resultSet = new ContentResult
{
Content = serializer.Serialize(errorReturn),
ContentType = "application/json"
};
}
return resultSet;
}
View and JS snippet:
//save project
function saveQuoteTemplate() {
var $templateBody = $("#quoteEntityItemsContainer"),
url = '#Url.Action("SaveQuoteTemplate", "Home")',
htmlTemplate = $templateBody.html(),
totalRecords = $("#quoteEntityItemsContainer").find("tr").length,
totalBadRecords = $("#quoteEntityItemsContainer").find("tr.table-danger").length,
templateName = $("#txtTemplateNameLabel").text(),
templateUserID = $("#txtUserID").text().trim(),
templateNotes = $("#taNotes").val(),
templateId = $("#txtTemplateNameLabel").attr("projectid"),
data = { 'htmlTemplate': htmlTemplate, "totalRecords": totalRecords, "totalBadRecords": totalBadRecords, "templateName": templateUserID + templateName, "templateNotes": templateNotes, "templateId": templateId };
updateProgressNotification('Saving project...');
console.log("MAX LENGTH: 2097152 | 4MB default. This string length is:" + htmlTemplate.length);
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify({ htmlTemplate, totalRecords, totalBadRecords, templateName, templateNotes, templateId }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
//Ajax evnts
success: _saveQuoteTemplateSuccessHandler,
error: _saveQuoteTemplateErrorHandler
});
$("#txtTemplateNameLabel").text(templateName);
storeProjectTempData();
}
What I am wondering, is how can I get around the max length issue that causes the failure server side before even hitting the controller, or can I change the JSON being sent to the controller, as just string param, string param2, and so on so it is not sent over as JSON?
Thanks much as always in advance!
To answer your question directly, here is how you can increase the sixe of a request body sent to the server.
<requestLimits maxAllowedContentLength="52428800" /> or
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 52428800; //50MB
});
see https://www.talkingdotnet.com/how-to-increase-file-upload-size-asp-net-core/
Add [FromBody] into your request action
public ActionResult SaveQuoteTemplate([FromBody]string htmlTemplate, int totalRecords, int totalBadRecords, string templateName, string templateDescription, string templateNotes, string templateId) { ... }

JavaScript - AJAX / 'Data' is empty / asp.net MVC

I found some similar questions but none of them resolve my problem.
The problem I have is that my data from my AJAX-call is empty but my controller return exactly I want him to return.
I tried to add a contentType, but neither contentType nor ContentType worked for me.
What am I doing wrong?
JavaScript:
function AddFunction() {
var ergebnis = "";
var zahl1 = $("#txt_1").val();
var zahl2 = $("#txt_2").val();
$.ajax({
async: false,
cache: false,
type: 'POST',
url: '/Calc/Add',
dataType: 'JSON',
data: {
'val_1': zahl1,
'val_2': zahl2
},
success: function (data) {
ergebnis = data.result;
alert(ergebnis);
},
error: function () {
alert("Fehler");
}
});
}
Controller:
public ActionResult Add(string val_1, string val_2)
{
string sUri = "http://192.168.111.173:35145/temppath/GVCalc/1.0/add";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(sUri);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"field_1\":\"" + val_1 + "\"," +
"\"field_2\":\"" + val_2 + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = DeserializeFromStream(httpResponse.GetResponseStream());
return Json(result);
}
Controller result:
{{
"result": 3
}}
Ajax data:
kinda empty / no result at all
Edit:
DeserializeFromStream Method:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
I solved my problem by sending a string and parse it in JavaScript. This worked fine for me :)
C#:
return Json(result.ToString());
JavaScript:
var ergebnis_json = JSON.parse(data)
ergebnis = ergebnis_json.result;
$("#ergebnis").val(ergebnis);
Thanks everyone for their help :)

How to send a MySQL parameter

Hello I have the following trigger:
CREATE TRIGGER `update` AFTER UPDATE ON `table 1`
FOR EACH ROW INSERT INTO table 2 (
Id,
Revision,
Purpose,
Change
)
VALUES
(
OLD.Id,
OLD.Revision,
OLD.Purpose,
#purpose_change /* user variable */
);
$$
DELIMITER ;
I am using C# WebService, Ajax, and JavaScript. Here is my C# methods for update (at the moment doesnt work)
"UPDATE table 1 SET Revision=#revision, Purpose=#purpose, #purpose_change=#change WHERE (Id =#id)";
Here starts the problem, because I dont know exactly how to send #purpose_channge.
Here is my Web Method.
[WebMethod(EnableSession = true)]
public string ActualizarAlerta(int id, string revision, string purpose, string change, int op)
{
string respuesta = "An Error Has Ocurred.";
try
{
UpdateAlert ua = new UpdateAlert(id, revision, purpose, change);
int resp = conn.UpdateAlerta(ua, op);
if (resp > 0)
respuesta = "Works!.";
}
catch (Exception ex)
{
respuesta = "An Error Has Ocurred: " + ex.Message;
}
return respuesta;
}
And here is my JavaScript with AJAX call.
$.ajax({
type: "POST",
url: urlServer + "ws_alerts.asmx/ActualizarAlerta",
data: '{' +
'"id":' + id +
',"revision":"' + rev +
'","purpose":"' + pur +
'","change":"' + change +
'","op":' + op + '}',
dataType: "json",
contentType: "application/json",
timeout: 60000,
error: function (xhr) {
bootbox.alert("Ocurrio un error al procesar la peticion.");
},
success: function (data) {
bootbox.alert(data.d);
}
});
id, rev, change, etc. Are $('#MyId').val()
I know that all the problem is in the Update query but I dont know how to do it correctly, how can I do that?
That is a mysql user variable, you must run a raw query before UpdateAlerta()
SqlCommand cmd = new SqlCommand("set #purpose_change = 'Purpose change to 1';", conn);
cmd.ExecuteNonQuery();
ps (I remember another related question here )

Categories