When I try to call C# Web service using jQurey, I am getting error "Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
I'm trying to send a call using ajax but in Chrome it is raising an error here is my code
JQuery:
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtItem").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "~/getitemdetails.asmx/GetItemNames",
data: "{'term':'" + document.getElementById('txtItem').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Match");
}
});
}
});
}
</script>
Web-Form HTML
<asp:TextBox ID="txtItem" CssClass="form-control col-md-3" runat="server"></asp:TextBox>
C# Web Method.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public List<string> GetItemNames(string term)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<string> listCountryName = new List<string>();
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetitemname", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter()
{
ParameterName = "@term",
Value = term
};
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCountryName.Add(rdr["raw_items"].ToString());
}
return (listCountryName);
}
}
}
How can I solve this error?
500 errors mean the code on the server crashed or failed for some reason.
That could be because you sent parameters it didn't expect, sent them in a format it didn't expect, values out of range, or the code on the server is poorly written and doesn't check the input parameters before trying to process them, or some combination of the above.
Try these possible solutions
var searchTerm= document.getElementById('txtItem').value;
var obj = { term : searchTerm};
var param = JSON.stringify(obj); // stringify the parameter?
public static List<string> GetItemNames(string term)
{
//your code...
}?
If none of the above works, check these links
https://www.aspsnippets.com/Articles/Call-Consume-Web-Service-ASMX-using-jQuery-AJAX-in-ASPNet.aspx
https://codehandbook.org/call-web-service-from-jquery-ajax/
above links explains how to call .asmx from jQuery Ajax.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly