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();
}
Related
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.
I have to call server side method update(input parameters) by using ajax call.when I am running the code my ajax is not loading.I want to update that data to Jquery Data table.please give me suggestions
$(document).on('click', '#btnsave', function () {
//have to get the emp_id
var id = $('#hdnid').val();
update(id);
});
function update(id) {
var name = $('#txtempname').val();
var sal = $('#txtsal').val();
var Dept_Id = $('#ddllist').val();
$.ajax({
//var Data = "{ empname:" + name + "}";
url: 'jdatatable.aspx/update',//my .aspx page name
type: "POST",
data: '{ id: ' + id + ',empname: "' + name + '", sal: ' +sal + ', Dept_Id: ' + Dept_Id + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (data) {
alert("successfully done");
table.ajax.reload();
$('#txtempname').val('');
$('#txtsal').val('');
$('#ddllist').val('');
},
"error": function (data, xhr, status) {
alert(status);
}
});
jdatatable.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
//mymethod
[System.Web.Services.WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public void update(int id, string empname, int sal, int Dept_Id)
{
string s = ConfigurationManager.ConnectionStrings["dbconn"].ToString();
List<UserDetails> li = new List<UserDetails>();
SqlConnection con = new SqlConnection(s);
con.Open();
SqlCommand cmd = new SqlCommand("sp_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#Emp_Name", empname));
cmd.Parameters.Add(new SqlParameter("#Sal", sal));
cmd.Parameters.Add(new SqlParameter("#Dept_Id", Dept_Id));
cmd.ExecuteNonQuery();
con.Close();
}
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?
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'},
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;
}