Ajax does not call c# function but it is success. How? - c#

I try to draw chart using google charts.
My code call c# through Ajax to retrieve data from database. The dubuger does not go to c# function but, it hit success function of ajax!
Aspx:
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawchart);
function drawchart(dataValues)
{
alert("drawing function");
alert(Object.keys(dataValues).length); //alert 3
alert(Object.keys(dataValues)); // alert Message, StackTrace,ExceptionType
alert(Object.values(dataValues)); // alert Authentication failed.,,System.InvalidOperationException
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].gender, dataValues[i].cnt]);
}
new google.visualization.PieChart(document.getElementById('myChartDiv')).draw(data, { title: "Google Chart in Asp.net using jQuery" });
}
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'Default.aspx/getGenderCount1',
data: '{}',
success:
function (data, textStatus, xhr) {
alert(data + "\t" + textStatus);
drawchart(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert("Error loading data!");
}
});
})
</script>
The alerts look likes this:
[object Object] success
drawing function
3
Message,StackTrace,ExceptionType Authentication
failed.,,System.InvalidOperationException
drawing function
1
isTrusted
true
c#:
public Static List<ParticipantGender> getGenderCount1()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
try
{
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
}
catch
{
}
finally
{
cmd.Dispose();
conn.Close();
}
return ListOfParticipantGender;
}
i also try the following:
public string getGenderCount1() and return the result as : var json
= JsonConvert.SerializeObject(ListOfParticipantGender); return json;
It draw the chart with "no data" . i figure out that When i debug "getGenderCount1" in c#, it does not debugged. But, when i put the code in the load function and trace the data coming from the database, it 100% right.
It seems like the ajax does not call the c# but it process the ajax success function!!!!

Related

Update dropdown list with ajax call in asp.net

I have web page with dropdown list "ListBox" with email address of users.
How do I make a function that update the dropdownlist "ListBox" everytime when I add new email user in the dropdown list ?
I have trying this solution without success because the dropdown list it emptied, instead of add new user.
This is my code :
nnewuser.txuser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("Ok");
alert(JSON.stringify(nnewuser));
$("[id*=ListBox1]").html(response);
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
Savepnusers
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = #String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
DropDownList
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = #String.Format(" SELECT ");
sql += String.Format(" LOWER(Email) AS UserEmail ");
sql += String.Format(" FROM ");
sql += String.Format(" tbl_email ORDER BY LOWER(Email) ASC; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "UserEmail";
ListBox1.DataValueField = "UserEmail";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}
There are 2 main problems here:
First, your Savepnusers method does not return anything, so you can't use response in AJAX calls. What you need is that re-initialize ListBox1 or append new item after Savepnusers complete successfully:
Secondly, it seems you can't send nnewuser as parameter correctly. You don't need to have pnnusers class instead just use string type as a parameter.
So server-side:
public static void Savepnusers(string nnewuser)
On client-side, you need to add dropdownlist item with jquery:
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers",
data: JSON.stringify({ nnewuser: txtUser }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//Since you can't use response object, you can append new item to dropdownlist
if (txtUser) {
$("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
See: asp dropdownlist dynamic value from javascript issue

Cannot get Jquery autocomplete to work in ASP.NET MVC

I cannot get autocomplete to work. I suspect this is because of my declaration of the URL in the Jquery method. How can I fix this issue?
This is the method in the HomeController:
public JsonResult Autocomplete(string term)
{
string connectionString = ConfigurationManager.ConnectionStrings["AbintegroModelContext"].ConnectionString;
List<string> CompanyName = new List<string>();
string query = string.Format("select distinct CompanyName from CompanyTable where CompanyName like '%{0}%'", term);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CompanyName.Add(reader["CompanyName"].ToString());
}
}
}
return Json(CompanyName, JsonRequestBehavior.AllowGet);
}
this is the Index view:
<body>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script>
$(function () {
$("#CompanyName").autocomplete({
source: function (request, response) {
var param = { companyName: $('#CompanyName').val() };
$.ajax({
url: '#Url.Action("Autocomplete", "Home")',
data: JSON.stringify(param),
datatype: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
console.log("Ajax Error!");
}
});
},
minLength: 2 //min legth of textbox input
});
});
</script>
...later on in the same view I have the html helper textbox CompanyName.
#Html.TextBox("CompanyName", null, new { #class = "indexTextbox" })
I haven't tried re-creating this problem on my end.
Have you used your browser's code inspector to see if any errors are returned?
Also you may try placing the jquery code inside a $(document).ready() function to see if that helps.

jQuery Autocomplete Not Working on Hosted Site

I am using the following code for autocompleting search textbox in my website. The code is working fine on localhost but when the site is hosted the "error" box pops up.
Script:
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetAutoCompleteData",
data: "{'location':'" + document.getElementById('ContentPlaceHolder1_txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and the function code is:
[WebMethod]
public static List<string> GetAutoCompleteData(string location)
{
List<string> result = new List<string>();
string connect = #"
Data Source=jaipurrooms.db.11458954.hostedresource.com; Initial Catalog=jaipurrooms;
User ID=xyz;
Password=xyz;";
using (SqlConnection con = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Location from Details where Location LIKE '%'+#location+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#location", location);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Location"].ToString());
}
return result;
}
}
}
I think you have to check your url in ajax request. Try to use the following syntax :
url: "./Index.aspx/GetAutoCompleteData",

jQuery AutoComplete multiple Output

I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.
I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.
eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.
I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.
JavaScript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
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.Title,
label: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
ASPX Code:
<div class="ui-widget" >
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
<asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>
CodeBehind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList(prefix)
.Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
return fetchEmail.ToList();
}
}
CompletionClass: (Excuse the naming)
public class Employee
{
public string Title { get; set; }
public string Name { get; set; }
public string value { get; set; }
public List<Employee> GetEmployeeList(string prefixText)
{
List<Employee> cmpList = new List<Employee>();
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
//var array = new ArrayList();
try
{
SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
}
}
command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
}
}
transaction.Commit();
}
catch (SqlException)
{
transaction.Rollback();
cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
//array.Add("Problem Getting Results.");
}
if (cmpList.Count == 0)
cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
//array.Add("Nothing to Display.");
//return array;
return cmpList;
}
}
Those modifications to your JavaScript should do the trick:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[name$="tbAuto"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
return false;
},
select: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
$('input[name$="tbHidden"]').val(ui.item.Title);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
};
});
</script>
The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.
Cool. I've been googling for this solution for days... excellent clean code!
Just a small remark: using jqueryUI 1.10, this
throws javascript exception.
.data('autocomplete')._renderItem = function(ul, item) {...
I've used
.data('ui-autocomplete')._renderItem = function(ul, item) {...
and everything works great.

Autocomplete Jquery function returning Internal Server Error while calling webservice

I am working on a project that requires to autocomplete textbox when some data is inputted and the data will be fetched from a database.
For this I created a webservice as -
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[ScriptService]
public class SearchIssues : System.Web.Services.WebService
{
//[ScriptMethod]
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
DataSet ds = null;
DataTable dt = null;
OracleConnection conn = null;
StringBuilder sb = new StringBuilder();
try
{
conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["Conn"].ToString());
sb.Append("select issueno from cet_sepcet where issueno like '");
sb.Append(prefixText);
sb.Append("%'");
OracleDataAdapter daRes = new OracleDataAdapter(sb.ToString(), conn);
ds = new DataSet();
daRes.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception exc)
{
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
}
}
The jquery ajax method I wrote is as -
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "SearchIssues.asmx/GetCompletionList",
data: request.term,
dataType: "json",
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
}
}))
//alert('Hello');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert(errorThrown);
}
});
},
minLength: 1
});
});
The webservice is running perfectly fine. But the problem comes when I try to call the webservice from the .aspx page. Its throws Internal server error.
I am not sure as where I am going wrong. Kindly help.
Thanks in advance.
Akhil
I advice you to use firebug to check whether your Post requests and responses this way you can easily debug your application.
This one in your code of ajax
data: request.term,
Should be actually
data: "{'prefixText':'" + request.term+ "'}",
Your service is expecting prefixText string as a parmeter, I assume request.term is the value.
Update :
I dont know what is not working at your end this works for me :
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service/WSDataService.asmx/GetStatesWithAbbr",
data: "{'name':'" + $(autocomplete).val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Name
}
}))
}
});
},
minLength: 1
});
});
</script>
....
<input id="autocomplete" />
Service :
[WebMethod]
public List<State> GetStatesWithAbbr(string name)
{
List<State> sbStates = new List<State>();
//Add states to the List
}
This code could throw exception, so please verify it one more time, probably table is not retrieved or something like it.
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
Place this line in your ajax:
data: '{ "prefixText": "' + request.term + '"}',
and it will work exactly as happened with me.

Categories

Resources