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 )
Related
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.
This question already has answers here:
jQuery Ajax error handling, show custom exception messages
(21 answers)
Closed 3 years ago.
I have an ajax call to a vb function. The vb function fails because the dataTable the query alludes to TABLE_ONE does not exist in the database.
I want the error message from the catch in vb to be returned to the 'error' of the ajax so that I can display that error to the user. The reason being that the error message in VB states precisely that the table does not exist in the database, whereas the error that is actually displayed to the user from here
error: function (a, b, c) {
alert("Ajax call to multiAjax failed: " + a);
}
does not tell the user the error is due to a table that doesn't exist. The ajax error message is useless.
How can I display the error message from the vb catch to the user?
Thanks
ajax:
function multiAjax(funcName, queryName, onSuccess) {
var result = null;
$.ajax({
type: "POST",
url: "WebService1.asmx/" + funcName,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
onSuccess(Response)
},
data: JSON.stringify({ "queryName": queryName }),
error: function (a, b, c) {
alert("Ajax call to multiAjax failed: " + a);
}
});
}
VB
<WebMethod(EnableSession:=True)>
Public Function getQueryNo()
Try
Dim queryNumberSql As String
Dim queryNo As Integer
Using dr As New DataReader(dif)
queryNumberSql =
"SELECT min(unused) AS unused
FROM (
SELECT MIN(t1.QUERY_NUMBER)+1 as unused
FROM TABLE_ONE AS t1
WHERE NOT EXISTS (SELECT * FROM TABLE_ONE AS t2 WHERE t2.QUERY_NUMBER = t1.QUERY_NUMBER+1)
UNION
-- Special case for missing the first row
SELECT 1
FROM TABLE_ONE AS t1
WHERE NOT EXISTS (SELECT * FROM TABLE_ONE WHERE QUERY_NUMBER = 1)
) AS subquery"
dr.ExecuteReader(queryNumberSql)
While dr.Read()
queryNo = Integer.Parse(dr("unused"))
End While
Return queryNo
End Using
Catch ex As Exception
Console.WriteLine($"Error trying to set query number: {ex}")
Return ex
End Try
End Function
This depends on your Library / Implementation you are using to make the request in the first place. Some libraries will reject if the server sends an error code, for example, 500.
Whilst considered bad practice, sending an error code might be what you want. (Just don't use this in an api!!)
Solution provided by #freedomn-m:
ajax:
function multiAjax(funcName, queryName, onSuccess) {
var result = null;
$.ajax({
type: "POST",
url: "WebService1.asmx/" + funcName,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
onSuccess(Response)
},
data: JSON.stringify({ "queryName": queryName }),
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}
});
}
VB:
Public Function getQueryNo()
Try
Dim queryNumberSql As String
Dim queryNo As Integer
Using dr As New DataReader(dif)
queryNumberSql =
"SELECT min(unused) AS unused
FROM (
SELECT MIN(t1.QUERY_NUMBER)+1 as unused
FROM CFG_QUERY_REPORT AS t1
WHERE NOT EXISTS (SELECT * FROM CFG_QUERY_REPORT AS t2 WHERE t2.QUERY_NUMBER = t1.QUERY_NUMBER+1)
UNION
-- Special case for missing the first row
SELECT 1
FROM CFG_QUERY_REPORT AS t1
WHERE NOT EXISTS (SELECT * FROM CFG_QUERY_REPORT WHERE QUERY_NUMBER = 1)
) AS subquery"
dr.ExecuteReader(queryNumberSql)
While dr.Read()
queryNo = Integer.Parse(dr("unused"))
End While
Return queryNo
End Using
Catch ex As Exception
HttpContext.Current.Response.StatusCode = 400
HttpContext.Current.Response.Write(ex)
End Try
End Function
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)
I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'
I have a problem where I am getting an id from a selected checkbox, then it sends it to a delete method and it then passes the id to a stored procedure. The problem I am having though is it is returning my id in a wrong format ("232,4323") instead of ("232","4323") so when it comes to passing in values to the stored procedure, it craps out because of the string format.
Here is my code in the aspx.
function doTheDelete(doIDeleteTimeTracker) {
var selectedTimeTrackerList = getSelectedTimeTrackerIDs();
if (selectedTimeTrackerList.length > 0) {
$.ajax({
type: "POST",
//url: "/Tasks/ViewTasks.aspx/deleteTasksAndLinkedItems",
url: '<%=ResolveUrl("~/TimeTrackers/ViewTimeTrackers.aspx/deleteSelectedTimeTracker")%>',
data: "{'DeleteTimeTracker' : '" + doIDeleteTimeTracker + "'," + "'TimeBill': ['" + selectedTimeTrackerList.join(',') + "']}",
//dataaaaaa
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var ss = data.d;
if (ss.length > 0) {
for (var i = 0; i < ss.length; ++i) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true });
alert(ss[i]);
}
}
$("#viewTimeTrackersGrid").flexReload();
showMessage('Successfully Removed Time Tracker');
},
error: function (data) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true });
alert('Error Deleting Time Tracker');
if (window.console) {
console.log(data);
}
}
});
} else {
showMessage('No time tracker(s) are selected.');
}
}
and here is my delete method in the code behind.
public static string[] deleteSelectedExpense(bool DeleteExpenses, String[] ExpId)
{
var rList = new List<string>();
//var canDeleteTasks = false;
//var canDeleteTrackers = false;
var canDeleteExpenses = false;
var investigatorID = (int)HttpContext.Current.Session["InvestigatorID"];
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
var cmd = new SqlCommand("p_Admin_Permissions_CanDeleteExpenses", conn);
cmd.Parameters.Add(new SqlParameter("#InvestigatorID", SqlDbType.Int));
cmd.Parameters["#InvestigatorID"].Value = investigatorID;
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
canDeleteExpenses = (bool)cmd.ExecuteScalar();
}
catch (SqlException sql)
{
if (!rList.Contains("Can not connect to the database. Please try again."))
rList.Add("Can not connect to the database. Please try again.");
}
catch (Exception ex)
{
if (!rList.Contains("An Error Occured"))
rList.Add("An Error Occured");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
if (canDeleteExpenses)
{
foreach (var expense in ExpId)// expense ends up beng ("232,423") instead of just taking 1 string at a time ("232").....("423")...
{
if (canDeleteExpenses)
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
cmd = new SqlCommand("p_CaseFiles_Expenses_DeleteExpenses", conn);
cmd.Parameters.Add(new SqlParameter("#ExpID", SqlDbType.Int));
cmd.Parameters["#ExpID"].Value = int.Parse(expense);
cmd.Parameters.Add("#Message", SqlDbType.NVarChar, 50);
cmd.Parameters["#Message"].Direction = ParameterDirection.Output;
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException sql)
{
if (!rList.Contains("Error Connecting to the Database. Unable To Delete Expense(s)."))
rList.Add("Error Connecting to the Database. Unable To Delete Expense(s).");
}
catch (Exception ex)
{
if (!rList.Contains("An Error Occured"))
rList.Add("An Error Occured");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
else if (!canDeleteExpenses)
{
rList.Add("You do not have permission to delete Expenses");
}
else
{
if (!rList.Contains("You do not have permission to delete the Expense(s)."))
rList.Add("You do not have permission to delete the Expense(s).");
}
}
}
return rList.ToArray();
}
I am guessing it could be in the "Data :" in the ajax call formatting for the array(I've tried a few things)
Try:
... 'TimeBill': ['" + selectedTimeTrackerList.join('","') + "']}" ...
Although a better solution would be to create a full javascript object with the required properties and apss it as an argument. BTW you may want to consider using something like PageMethods instead of jQuery if you are calling this method only on this page.
There is no reason to create a string to send as Data, you can send a json object instead.
Data: {
DeleteTimeTracker: doIDeleteTimeTracker,
TimeBill: selectedTimeTrackerList
}, ...
thanks for the help gents. I managed to fix it. Solution was to do this:
"'ExpId': ['" + selectedExpensesList.join('\',\'') + "']}",
instead of :
"'ExpId': ['" + selectedExpensesList.join(',') + "']}",
adding the extra ' seemed to work. It then manages to take each id seperately instead of taking the entire array and pooping on me