I am using ajax to call a [WebMethod].But it doesn't Works.Code i used is
ASPX page
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: '{name: "' + document.getElementById("lbcb5").innerHTML + '" }', Value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
Aspx.cs page
[WebMethod]
public static string GetCurrentDateTime(string name)
{
return "Hey! " + name + Environment.NewLine + "The Current Date & Time is: "
+ DateTime.Now.ToString();
}
Thanks in advance
you don't need quotes on data, do like this:
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: {name: document.getElementById("lbcb5").innerHTML},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert(response)
},
failure: function (response) {
alert(response.d);
}
});
Did you add a ScriptManager in you aspx page?
I think you should try to add it with the attribute EnablePageMethods="true"
try this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
"When i use ScriptManager shows an error Only one instance of a ScriptManager can be added to the page."
when this type of error is thrown, then use scriptmanager proxy
<ajax:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</ajax:ScriptManagerProxy>
--------------************DEFAULT.ASPX************--------------
<script type="text/javascript">
function YolAl(yol) {
deger='<%=ResolveUrl("~/'+ yol +'") %>'
return deger;
}
</script>
*******************------USERCONTROL CALL JS-------************************
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
deger += 1;
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
}
});
$(document).ready(function () {
deger += 1;
RepeaterFnc("DurumGuncelle.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("IlanlarTab.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10Ilanlar.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
});
function TakipEtYenileFnc() {
$('#SagDivFavoriId').html('');
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
}
function RepeaterFnc(usercontrol, deger, DivName,FuncName) {
$('#ajaxloading').show();
var NextId = deger;
$.ajax({
url: FuncName,
type: "POST",
data: "{usercontrol:'" + usercontrol + "', NextId:'" + NextId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
OnSuccess1(msg, DivName);
},
error: function (msg) { OnError1(DivName); }
});
deger = parseInt(deger + 1);
}
function OnSuccess1(data, DivName) {
$("#" + DivName).html($("#" + DivName).html() + data.d);
$('#ajaxloading').hide();
}
function OnError1(divname) {
return false;
$("#" + divname).html("Error!");
}
Related
Here is my ajax call
$(document).ready(function () {
$("#btnSubmit").click(function () {
alert("I am in ?");
$.ajax({
type: "POST",
url: "TestNew2.aspx/DisplayData",
data: "{}",
contentType: "application/x-www-form-urlencoded",
dataType: "text",
//success: function (msg) {
// // Replace the div's content with the page method's return.
// $("#btnSubmit").text(msg.d);
// alert(msg.d);
//}
success: function (result, status, xhr) {
document.getElementById("lblOutput").innerHTML = xhr.responseText
},
error: function (xhr, status, error) {
alert(xhr.error);
}
});
});
});
and my Web method[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString();
}
Getting aspx page when trying to call web method on aspx page.Here is the jQuery code
Can any one point out what may be wrong.Because the web method is not getting called.
Try Like
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
OR
jQuery.ajax({
type: "POST",
url: "Login.aspx/checkUserNameAvail",
contentType: "application/json; charset=utf-8",
data: "{'iuser':'" + userid + "'}",
dataType: "xml",
success: function (msg) {
$(msg).find("Table").each(function () {
var username = $(this).find('UserName').text();
if (username != '') {
//window.location.replace('/iCalendar.aspx');
alert('This username already taken..');
$("#reguser").val('');
$("#reguser").focus();
}
else {
}
});
},
error: function (d) {
}
});
.CS
[WebMethod(enableSession: true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string checkUserNameAvail(string iuser)
{
try
{
iCalendarClass iC = new iCalendarClass();
DataSet ds = iC.checkUserNameAvail(iuser);
return (ds.GetXml());
}
catch
{
return null;
}
}
Using .NET here's what I've got.. The right results are returned, but they're all combined together into one long string. How can I make it so I can select one item at a time from the results returned? I know my source in the javascript is configured incorrectly. Any help would be appreciated. Thanks
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetEmails(string emailContains)
{
LoginSet logins = staticLogic.searchLogins(staticClient, new SearchCriteriaSet());
List<BaseEntry> loginList = logins.Where(x => ((LoginEntry)x).LoginEMail.Contains(emailContains)).ToList();
List<string> emails = new List<string>();
for (int i = 0; i < loginList.Count(); ++i)
{
string email = ((LoginEntry)loginList.ElementAt(i)).LoginEMail;
emails.Add(email);
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//string json = serializer.Serialize(emails.ToArray());
return emails.ToArray();
}
UI:
<tr><td>Destination:</td>
<td>
<div class="ui-widget">
<input type="text" name="EMailReportDestination" id="EMailReportDestination" size="60" runat="server" />
</div>
</td>
</tr>
JQuery:
$('#EMailReportDestination').autocomplete({
source: function (request, response) {
$.ajax({
url: '/reports/editemailreport.aspx/GetEmails',
type: 'POST',
dataType: 'json',
data: "{'emailContains':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//console.log('autocomplete success: ' + data);
response($.map(data, function (item) {
return {
label: item,
value: item
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("autocomplete error: " + xhr.status + ", " + thrownError);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui.item ? "selected: " + ui.item.label : "nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I tried and I don't know array returned in data.d. try to change
response($.map(data, function (item)
to
response($.map(data.d, function (item)
I'm working on my collage project (Web app written in C#) and I'm using javascript
to dynamically add hotels with details and image using following code:
$.ajax({
type: 'POST',
url: 'WebServiceBooking.asmx/Hotels',
data: "{'stars':'" + stars + "','countryid':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.hotels').empty();
var hotels = data.d; //getting List<Hotel> from [WebMethod](works)
window.t = "";
window.ImageID = "";
$.each(hotels, function (index, hotel) {
$.ajax({ //this ajax is getting Image for specified hotel.HotelID
type: 'POST',
url: 'WebServiceBooking.asmx/HotelImage',
data: "{'hotelid':'" + hotel.HotelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
window.ImageID = data.d;
//$('.hotels-image').attr('src', 'ImageHandlerFromID.ashx?ImageID=' + data.d);
},
complete: function (xhr, status) {
window.t += "<div class='hotel clearfix'><h3><a href='hotel.aspx?HotelID=" + hotel.HotelID + "'>" + hotel.HotelName + "</a></h3><p class='hotelAddress'>" + hotel.HotelAddress + "</p><p class='hotelPhone'>" + hotel.HotelPhone + "</p>";
window.t += "<img class='hotels-image' src='ImageHandlerFromID.ashx?ImageID=" + window.ImageID + "'/>";
window.t += "</div>";
console.log(window.ImageID);
}
});
console.log(ImageID);
});
console.log(window.t);
},
complete: function (xhr, status) {
$('.hotels').append(window.t);
}
});
After several attempts, neither complete function works.
The complete call will only complete the first ajax call. Not the one's in the for loop. If you want to check if all requests are done use $.when.
var requests = [];
var overall_data = {"hotels" = [], "hotel_images" = []}
var main_request = $.ajax({
type: 'POST',
url: 'WebServiceBooking.asmx/Hotels',
data: "{'stars':'" + stars + "','countryid':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.hotels').empty();
var hotels = data.d; //getting List<Hotel> from [WebMethod](works)
overall_data["hotels"] = hotels
window.t = "";
window.ImageID = "";
$.each(hotels, function (index, hotel) {
var hotel_request = $.ajax({ //this ajax is getting Image for specified hotel.HotelID
type: 'POST',
url: 'WebServiceBooking.asmx/HotelImage',
data: "{'hotelid':'" + hotel.HotelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
window.ImageID = data.d;
overall_data["hotel_images"].push(data)
//$('.hotels-image').attr('src', 'ImageHandlerFromID.ashx?ImageID=' + data.d);
}
});
requests.push(hotel_request)
console.log(ImageID);
});
console.log(window.t);
}
});
requests.push(main_request);
$.when.apply(null, requests).done(function(){
// Do your stuff with overall_data
})
I'm trying to jquery dropdownlist with this result set of webservice, the getYears function is returning list of years 2013,2012,2011.... in List<string> for but when I bind it with ddlyears the values coming up as 1,2,3,4,5,6
$.ajax({
type: "POST",
url: "../WebService.asmx/getYears",
data:"{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
for (var myVar in msg.d) {
$('#ddlyears').append("<option value='" + myVar.toString() + "'>" + myVar.toString() + "</option>");
}
},
error: function (jqerr) {
errorCaller(jqerr);
}
});
Try this:
success: function (msg) {
$.each(msg.d, function (k, value) {
$('#ddlyears').append("<option value='" + value + "'>" + value + "</option>");
});
}
I am trying to execute a method in ASP.NET from Jquery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyMessages.aspx?id=66&epslanguage=sv/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
}
})
code behind:
[WebMethod]
protected void test()
{
test.Text = "works";
}
I get errormessage redayState: 4 and status 200 when I do this. I don't understand the problem. I am vey new at this. :)
data: "{}", should be just data: {}, or just remove it if not in use,,..
as a first your method should be static and public
so instead of this
[WebMethod]
protected void test()
{
test.Text = "works";
}
it should be
[WebMethod]
public static void test()
{
test.Text = "works";
}
this is the first fix
the second you can't access the test.text
so if u wanna make sure it works you can
write it in this way
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
so your final code should be like this
[WebMethod]
public static void test()
{
//test.Text = "works";
}
and Ajax method
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
I did change the URL for u
and if you wanna pass parameters you pass them on Data Section of Ajax method
some thing like this
'{"fname":"' + fname + '","lname":"' + lname + '","email":"' + email + '","address":"' +
I wish it helps you
address + '"}'