Json Ajax Parameter pass & Webmethod not firing - c#

In my Ajax function i tried to pass a int Parameter to the Webmethod but it's not success.
Here i paste my code
Ajax Function
$('#drpChurchNames').on('change', function () {
//alert($(this).val());
LoadFathersToChurch(churchId)
});
function LoadFathersToChurch(churchId) {
var url = '<%=ResolveUrl("WebMethods.aspx/GetFatherNames") %>';
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ Id: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
Here is my WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<FatherNames> GetFatherNames(int ChurchId)
{
List<FatherNames> FathersList = new List<FatherNames>();
try
{
SqlCommand comChurchNames = new SqlCommand("GetFathers", conDB);
comChurchNames.CommandType = CommandType.StoredProcedure;
comChurchNames.Parameters.Add("#Id", SqlDbType.Int);
comChurchNames.Parameters["#Id"].Value = ChurchId;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comChurchNames.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
FathersList.Add(new FatherNames
{
Id = (int)r["Id"],
FatherName = r["FatherName"].ToString()
});
}
}
Here is my SP
ALTER PROCEDURE [dbo].[GetFathers]
#SelectIndexName int
AS
BEGIN
Select * from dbo.RevFathers
Where ChurchId = #SelectIndexName
END

You are passing Id as parameter and the correct is ChurchId just like webmethod signature GetFatherNames(int ChurchId).
There is the correct way:
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ ChurchId: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});

Is your webmethod actually getting executed? If it is and you think it should be returning data, it could be that your webmethod is not returning JSON, thus jQuery may be generating and error and not firing success.
I have this in my global.asax to configure the output for both XML and JSON:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
Placed in app_start
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
I know this isn't a direct answer, but I can't post comments yet so I would have just asked the above question first about is the webmthod getting called.

Related

To fill a ComboBox (ajaxToolkit) from an Ajax WebMethod

On my ASPX page I have the following ComboBox that should be filled from an Ajax WebMethod.
<ajaxToolkit:ComboBox ID ="cbMembers" runat="server"></ajaxToolkit:ComboBox>
The WebMethod that fills the ComboBox is called as follows:
$.ajax({
type: "POST",
url: functions.aspx/members",
data: "{SearchInput: '" + SearchInput + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- My problem is here -- );
})
}
});
WebMethod
List<ListItem> members = new List<ListItem>();
...
if (Reader.HasRows)
{
while (Reader.Read())
{
members.Add(new ListItem
{
Value = HttpUtility.HtmlEncode((string)(Reader["name"])),
Text = HttpUtility.HtmlEncode((string)(Reader["name"]))
});
}
}
return members;
...
The data is retrieved correctly from the WebMethod. I tested it. But my problem is to fill the list items in the ComboBox. Any advice?
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- How to append the data here? --);
})
}
Try this
$.each(r.d, function () {
cbMembers.append($("<option>",{value:"1",text:"Gloria"}));
})
Try this
$.each(r.d, function () {
cbMembers.append($("<option></option>").val(this['Value']).html(this['Text']));
}

JSON Invalide primitive

I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}

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",

Pass paramater to webservice on ajax

I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',

pass to javascript class object is serialized in code behind

JavaScriptSerializer jss = new JavaScriptSerializer();
var seferim = jss.Serialize(sefer);
string asds = seferim.ToString();
asds = HttpUtility.HtmlEncode(asds);
function otobusGetir(id, b, i) {
id = encodeURI(id);
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: '{"id":"' + id + '","Binis":"' + b + '","Inis":"' + i + '"}',
success: function () { },
error: function () { }
})
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
string a = id;
string b = HttpUtility.HtmlDecode(id);
return null;
}
The problem is javascript function cannot take parameter(Uncaught SyntaxError: Unexpected token ILLEGAL) which is serialized.How i can totally done tihs job?
The problem is that this is not working while javascript function run it can not take argument,how can totaly don this job
Try like this:
function otobusGetir(id, b, i) {
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({ id: id, Binis: b, Inis: i }),
success: function () { },
error: function () { }
});
}
and to call the function:
otobusGetir(123, 'foo bar', 'baz');
and the page method:
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
// don't use any Html decoding here. The parameters will
// already be properly formatted so you can use them directly
return null;
}

Categories

Resources