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
})
Related
I have following code in my CenterDetail.aspx page
function myFunction(id) {
console.log(2);
var myindex = window.ContentPlaceHolder1_ddCountryId.selectedIndex;
console.log(myindex);
var selectedName = window.ContentPlaceHolder1_ddCountryId.options[myindex].text;
console.log(selectedName);
var loc = window.location.href;
console.log(loc);
$.ajax({
type: "POST",
url: loc + "/BindState",
data: { id : id },
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
and following method is in my code behind file.
[WebMethod]
public static string BindState(int id)
{
var states = new StateProvinceCollection().Where(StateProvince.Columns.CountryId = Convert.ToString(id), true).ToList();
string tag = "<select id='StateProvinceId' name='StateProvinceName'>";
tag += "<option value=''>select</option>";
foreach (var item in states)
{
tag += "<option value='" + item.StateProvinceId + "'>" + item.StateProvinceName + "</option>";
}
tag += "</select>";
return tag;
}
everything is still it show http://musicclass/Account/Management/Center/CenterDetail.aspx/BindState 404 not found error.
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!");
}
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 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 + '"}',
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 + '"}'