JQPlot and C# response issues - c#

I have a JQPlot chart, calling a WebMethod is c#. The WebMethod calls out to a sp and returns a date and an amount. i am having issues with the returned data. Firebug reports the following:
SyntaxErrorL JSON.parseLunexpected character
var = series = JSON.parse(data.d);
The response from my WebMethod is :
{"d":[{"__type":"GlobalClasses+jqplotModel","amount":25000.00,"ValueDate":"2013-03-27"},
{"__type":"GlobalClasses+jqplotModel","amount":10000.00,"ValueDate":"2013-03-27"},
{"__type":"GlobalClasses+jqplotModel","amount":200000.00,"ValueDate":"2013-03-27"},
{"__type":"GlobalClasses+jqplotModel","amount":69900.00,"ValueDate":"2013-03-27"},]}
WebMethod code:
[WebMethod]
[ScriptMethod]
public static List<GlobalClasses.jqplotModel> BuildCharts()
{
List<GlobalClasses.jqplotModel> newChart = new List<GlobalClasses.jqplotModel>();
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings
["Conn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("ChartData_Sel", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#senderBIC", SqlDbType.VarChar, 11).Value = "ARBUGB2LXXX";
cmd.Parameters.Add("#messageType", SqlDbType.VarChar, 3).Value = "103";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader dreader = cmd.ExecuteReader())
{
while (dreader.Read())
{
GlobalClasses.jqplotModel dataSet = new GlobalClasses.jqplotModel()
{
amount = dreader.GetDecimal(0),
ValueDate = dreader.GetString(1)
};
newChart.Add(dataSet);
}
}
}
}
return newChart;
}
being called from my HTML page like this :
$.ajax({
type: "POST",
url: "Default.aspx/BuildCharts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var series = JSON.parse(data.d);
chart = $.jqplot("chart", [series], chartOptions);
}
});

Your returned JSON is not well formated because you are having an extra , at the end of the last item. You can check it here. If you remove it you should not have parsing errors.
Try this instead
{"d":[{"__type":"GlobalClasses+jqplotModel","amount":25000,"ValueDate":"2013-03-27"},{"__type":"GlobalClasses+jqplotModel","amount":10000,"ValueDate":"2013-03-27"},{"__type":"GlobalClasses+jqplotModel","amount":200000,"ValueDate":"2013-03-27"},{"__type":"GlobalClasses+jqplotModel","amount":69900,"ValueDate":"2013-03-27"}]}

Related

SyntaxError: Unexpected token < in JSON at position 4 in ajax call in asp.net

I am binding data on dropdown index change event using ajax call using asp.net web form
following my Ajax code
var e = document.getElementById("<%=ddlEducation.ClientID%>");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
if (value == "0") {
$('#dvRecords').empty();
alert("Please Select Education");
return false;
}
var obj = { "iEduid": value};
var myJSON = JSON.stringify(obj);
//Filling Grid View
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'EditProfile.aspx/BINDEducationDATA',
data: myJSON,
dataType: 'JSON',
success: function (response) {
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value = response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value = response.d[i].Edu_Description
},
error: function (xhr, status, error) {
console.log(xhr);
alert(status);
alert(error);
}
});
when it it executing i am getting 1st error is parsererror next i am getting error saying Unexpected token < in JSON at position 4.
above is my C# code
[WebMethod]
public static List<EduDesc> BINDEducationDATA(string iEduid)
{
List<EduDesc> details = new List<EduDesc>();
DataTable dtManager = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd = new SqlCommand("Select Edu_Stream,Edu_Description from tbl_education WHERE ID='" + iEduid + "'", con);
da.SelectCommand = cmd;
da.Fill(dtManager);
}
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
return details;
}
any help will appreciated.
There are a couple areas of concern.
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
// - extra parentheses.
// - here you use logs.Edu_desc but in 'success' (below) you use Edu_Description.
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
success: function (response) {
// here you're looking for [i], but what is i? you need an integer.
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value =
response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value =
response.d[i].Edu_Description
},
In the success function, do a console.log(d) to double-check the results.
hth.

Auto Suggestion Search Box in master page not working

I'm attempting to implement an autocomplete search feature in the master page of my project to be used by other pages inheriting the master page but the function returns an error despite there being data in my database table to return. I have checked that the table name, textbox ID and column is correct but I'm still not sure what the problem is. Any help would be appreciated!
This is the script in my master page file:
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#searchTerm").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetmovieTitle",
data: "{'name':'" + document.getElementById('searchTerm').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("No Match");
}
});
}
});
}
</script>
This is the content of my webservice page:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetmovieTitle(string name)
{
List<string> mResult = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\QACinema\\QACinema\\App_Data\\QACinemaHomeCopy.mdf';Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.CommandText = "Select name from movies where name LIKE '+#name+'%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", name);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
mResult.Add(dr["name"].ToString());
}
return mResult;
}
}
}
}

Textbox Change Event not working

I have two Textboxes,I'm trying to fill the Second Textbox at change Event of Textbox1
Eg:
I have to fill the Customer Name when i type the Customer Code at TextBox1.
MY Script:
$(document).ready(function() {
userCodeChangeEvent();
});
function userCodeChangeEvent() {
$('#<%=txtCustomerCode.ClientID %>').change(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Customer_Bill.aspx/GetNameByCode",
data: "{'CusName':'" + document.getElementById('<%=txtCustomerCode.ClientID %>').value + "'}",
dataType: "json",
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').value = data.d;
},
error: function(result) {
alert("No Match");
}
});
});
}
C#:
[WebMethod]
public static string GetNameByCode(string CusName)
{
// List<string> empResult = new List<string>();
string empResult = "";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select user_name From tbl_member_Registration where user_code=#SearchEmpName";
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#SearchEmpName", CusName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
empResult=dr["user_name"].ToString();
}
con.Close();
return empResult;
}
}
}
but it doesn't working .How do i Solve this?
In client side 2 things you should notice :
1- $(...).val(data.d);
2- use "keyup" instead "change" because change will not be fired while the user is typing.
In Server side make sure that you enabled "ScriptService" by adding the [System.Web.Script.Services.ScriptService] attribute to the web service class (code behind the asmx) as the following:
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService
{
[WebMethod]
public static string GetNameByCode(string CusName)
{
...
}
}
In your success function use val() instead of val= like this
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').val(data.d);
}
,
And if necessary change this line also
data: "{'CusName':'" + $('#<%=txtCustomerCode.ClientID %>').val() + "'}",

How to pass parameter in Json in data?

I have a text box in aspx page. from that i need to send the text of the textbox in function in Json For that i have a method in server side.
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
DataTable dt = new DataTable();
List<OfficeDetails> details = new List<OfficeDetails>();
using (SqlConnection con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select OfficeName,City,Country from Office where OfficeName like '%" + officename + "%'", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
OfficeDetails Office = new OfficeDetails();
Office.OfficeName = dtrow["OfficeName"].ToString();
Office.City = dtrow["City"].ToString();
Office.Country = dtrow["Country"].ToString();
details.Add(Office);
}
}
}
return details.ToArray();
}
and in .aspx page I have
$('#btnSearch').click
(
function () {
var searchtext = $("#txtSearch").val();
alert(searchtext);
$.ajax(
{
type: "POST",
url: "Gridview.aspx/BindSearchDatatable",
data: "{officename : New}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
}
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}
);
return false;
}
);
Now my Question is I send the Parameter in data but i am getting an error The function is running well.I have tested it without parameter so its running well.so i thing some wrong things is going on passing the text value Of textbox in function.
You are sending an invalid JSON. Replace:
data: "{officename : New}"
with:
data: "{officename : 'New'}"
or even better use the JSON.stringify method which wil take care of properly encoding the values:
data: JSON.stringify({ officename : 'New' })
Also please fix your server side script and use parametrized queries because your code is vulnerable to SQL injection attacks and if you put this code into the wild, you might find yourself one day with a missing database. Oh and you really don't need any DataTables:
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
using (var con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT OfficeName, City, Country FROM Office WHERE OfficeName LIKE #officename";
cmd.Parameters.AddWithValue("#officename", "%" + officename + "%");
using (var reader = cmd.ExecuteReader())
{
var details = new List<OfficeDetails>();
while (reader.Read())
{
var office = new OfficeDetails();
office.OfficeName = reader.GetString(reader.GetOrdinal("OfficeName"));
office.City = reader.GetString(reader.GetOrdinal("City"));
office.Country = reader.GetString(reader.GetOrdinal("Country"));
details.Add(office);
}
return details.ToArray();
}
}
}
Replace:
data: "{officename : New}"
with:
data: {officename : 'New'},

JQUery autocomplete in ASP.Net Webservice

This is driving me crazy , I just keep getting the message "error" nothing else. I had this autocomplete working with AJAX Toolkit, but I want to try JQuery, I have very little experience with JQuery. Here is WebService code:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public static string GetNames(string prefixText, int count)
{
Trie ArtistTrie = new Trie();
if (HttpContext.Current.Cache["CustomersTrie"] == null)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand();
comm.CommandText = "SELECT * FROM TopArtists ORDER BY name ASC";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = comm;
comm.Connection = conn;
conn.Open();
da.Fill(dt);
conn.Close();
Trie newtrie = new Trie();
foreach (DataRow dr in dt.Rows)
{
// topartists.Add(dr[0].ToString());
newtrie.Add(dr[0].ToString());
}
HttpContext.Current.Cache["CustomersTrie"] = newtrie;
}
ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];
List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
List<Band> list1 = new List<Band>();
foreach (string a in list)
{
Band newband = new Band();
newband.Name = a;
list1.Add(newband);
}
string json = JsonConvert.SerializeObject(list1, Formatting.Indented);
return json;
}
Here is JQuery Code:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#tb1").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term ,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
})
</script>
Well for one, your jQuery code has errors, including a missing semicolon at the end and an unnecessary function wrapping the autocomplete, try:
<script type="text/javascript">
$(document).ready(function() {
$("#tb1").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
for the ajax part, the return need to be in array, string[]
sample code,
[WebMethod]
public string[] area(string prefixText)
{
List<string> listString = new List<string>();
using (SqlConnection con = new SqlConnection("Initial Catalog=EMS;Server=S-CEMSDB01;User ID=sa;Password=sqltest"))
{
SqlCommand cm = new SqlCommand("select distinct eqp_location from EQUIPMENT where eqp_location like '" + prefixText + "%' order by eqp_location", con);
con.Open();
SqlDataReader dr = cm.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listString.Add((dr["eqp_location"].ToString()));
//c.FullName, serializer.Serialize(c))
}
}
dr.Close();
dr.Dispose();
con.Close();
}
string[] str = listString.ToArray();
return str;
}

Categories

Resources