How to pass parameter in Json in data? - c#

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'},

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.

How to create dependency dropdownlist in ajax

I use below code .I have 2 dropdownlist it work fine.but problem is second drodownlist value doesnt store in database when i click on update button.It gives null value reference unhandled error.On form.aspx.cs i take that value on label cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString()); but in this it takes null value
<script type="text/javascript">
$(function() {
//$('#<%=DropDownList2.ClientID %>').attr('disabled', 'disabled');
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$('#<%=DropDownList1.ClientID %>').change(function() {
var country = $('#<%=DropDownList1.ClientID%>').val()
$('#<%=DropDownList2.ClientID %>').removeAttr("disabled");
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'country':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
},
error: function(data) {
alert('Something Went Wrong')
}
});
});
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$("#DropDownList2").children("option").is("selected").text()
$('#<%=DropDownList2.ClientID %>').change(function() {
var stateid = $('#<%=DropDownList2.ClientID%>').val()
var myVar =('#DropDownList2').find(':selected').text();
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'state':'" + post_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
$("option:selected", myVar).text()
},
error: function(data) {
alert('Something Went Wrong')
}
});
})
})
</script>
and my c# code is
private void Bindcategorydown()
{
String strQuery = "SELECT [dept_no],[department_name] FROM [first].[dbo].[dept_add]";
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "department_name";
DropDownList1.DataValueField = "dept_no";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Department", "0"));
con.Close();
}
}
}
[WebMethod]
public static string BindPosts(string country)
{
StringWriter builder = new StringWriter();
String strQuery = "SELECT [post_id],[post_name] FROM [first].[dbo].[add_post] where group_id=#dept_no";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("#dept_no", country);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["post_name"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["post_id"] + "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}
and on update button i use this
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.Text);
If the problem persists, send us the stack trace of the error.

System.InvalidOperationException: Missing parameter

I try to send parameter to asmx(web service file) but i get error about "System.InvalidOperationException: Missing parameter". Please help me to solve this problem and thank you so much
this is my ajax function
$("#dd_address").change(function () {
var rowID = $(this).find(':selected').val();
console.log(rowID);
$.ajax({
url: "WebService.asmx/queryCity",
data: {
id: JSON.stringify(rowID),
},
type: "POST",
dataType: "json",
contentType: "application/json; charset-utf-8",
success: OnSuccess,
error: OnError
});
});
this is my code from asmx
DataTable result;
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string queryCity(string id)
{
DataTable dt;
SqlConnection MRK_Conn = new SqlConnection(#"Data Source=192.168.24.30;Initial Catalog=Marketing_Data;Persist Security info=True;User ID=sa;Password=sa");
SqlCommand cmd = new SqlCommand();
SqlDataReader sql_dr;
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
MRK_Conn.Open();
cmd = new SqlCommand("select [City RowID], [City Description] from City where [Des Ref Province] = '" + id + "'", MRK_Conn);
dt = new DataTable();
sql_dr = cmd.ExecuteReader();
dt.Load(sql_dr);
sql_dr.Close();
MRK_Conn.Close();
result = dt;
return serializer.Serialize(result);
}
and in web config file
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Problem in your code is in the way you are passing the input parameter to the method, change it like this:-
var rowID = { "id" : $(this).find(':selected').val() };
Then, pass it like this in the method:-
data : JSON.stringify(rowID)
Apart from this your ADO.NET code is open for SQL Injection attack, so please use parametrized query instead.
I have updated your code, below code works for me. Please remember I have hardcoded var rowID = 20; make your changes as you need.
Please let me know if you have any questions.
ASPX Page button:
<input type="button" value="submit" onclick="sendrequest();" />
Javascript "sendrequest" Function:
<script>
function sendrequest()
{
var rowID = 20;
console.log(rowID);
$.ajax({
url: "WebService.asmx/queryCity",
data: '{"id":"' + rowID + '"}',
type: "POST",
dataType: "json",
contentType: "application/json; charset-utf-8",
success: function (data) {
var xmlDoc = $.parseXML(data.d);
var xml = $(xmlDoc);
var city = xml.find("Table1");
alert(city.text());
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error: ' + xhr.status + ' ' + thrownError);
}
});
}
</script>
Webservice Method:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string queryCity(string id)
{
DataSet ds = new DataSet();
DataTable dt= new DataTable("Table");
SqlConnection MRK_Conn = new SqlConnection(#"Data Source=KEVAL;Initial Catalog=SampleDatabase;Persist Security info=True;User ID=sa;Password=sa123");
SqlCommand cmd = new SqlCommand();
SqlDataReader sql_dr;
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
MRK_Conn.Open();
cmd = new SqlCommand("select [City RowID], [City Description] from City where [Des Ref Province] = '" + id + "'", MRK_Conn);
dt = new DataTable();
sql_dr = cmd.ExecuteReader();
dt.Load(sql_dr);
sql_dr.Close();
MRK_Conn.Close();
ds.Tables.Add(dt);
return ds.GetXml();
}

I want to fetch some data from database on click of the link using jquery but on clicking link getting an alert with undefined type

I want to get data from the database based on the text of that link on click of the link but getting undefined alert message.
I'm new to jquery so please help me out with this if anybody can. Thanks in advance.
here is the code snippet
jquery
<script type="text/javascript">
var name;
$(function () {
$("[id*=Menu] td a").click(function () {
name=$(this).text().trim();
GetRecords();
//alert(name);
});
});
function GetRecords() {
$("#loader").show();
$.ajax({
type: "POST",
url: "kioskstore.aspx/GetPrice",
data: '{name: ' + name + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var productsInfo = xml.find("Products_Info");
productsInfo.each(function () {
var customer = $(this);
$(".price").html(customer.find("Products_Price").text().trim());
});
$("#loader").hide();
}
</script>
asp.net
<div style="margin-top:25px;height:40px;float: left;margin-left:40px;font-family:cursive;font-size:24px;color:#ffe476;">
<asp:Label runat="server" CssClass="price" Text=""></asp:Label>
</div>
and the code behind C#
[WebMethod]
public static string GetPrice(string name)
{
return GetPriceData(name).GetXml();
}
public static DataSet GetPriceData(string name)
{
string query = "select * from Product_Info where Product_Name=#pname";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#pname", name);
//cmd.Parameters.Add("#PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd);
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Product_Info");
return ds;
}
}
}
}
I think you are missing enclosing quotes for string.
Use
data: '{name: "' + name + '"}'
instead of
data: '{name: ' + name + '}'
Responding to your comment:
That message means you are requesting an incorrect URL. Please try with this.
url:document.location + '/GetPrice'
Please confirm whether your request is going to the correct URL. You can use the network monitor component of a browser development tools or an HTTP proxy like Fiddler. If you have chrome, you can check this using the Network tab of the Development Tools. Additionally you can make use of a chrome plugin called Postman to invoke HTTP request to check if they are working or not.
if you are calling from the same page?

JQPlot and C# response issues

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"}]}

Categories

Resources