I'm trying to call the jQuery function $.get() to make a call to my WebMethod but it's only hitting the Page_Load event in the code behind. I can see the request being sent out in firebug to /admin/manage-users.aspx/deleteUser?u=user1 but it never hits the WebMethod.
jquery
$('#delete').each(function () {
$(this).click(function () {
var userName = $(this).closest('tr').find('span.userName').text();
$.get('/admin/manage-users.aspx/deleteUser', { u: userName });
});
});
aspx.cs
[WebMethod]
public void deleteUser() {
string userName = Request.QueryString["u"];
if(!string.IsNullOrEmpty(userName)) {
if(Membership.DeleteUser(userName))
Response.Redirect(Request.Url.ToString());
}
}
SOLUTION
I gave credit to bugz below because he pointed me in the right direction.
In order for your [WebMethod] to work your method within the aspx has to be static
Here is a link for more information
More Information
$.ajax({
type: "POST",
url: "'/admin/manage-users.aspx/deleteUser'",
data: "{'userName ' : '" + userName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//do something on success
},
error: function(ex) {
//do something on failure
}
});
Also on success if you are returning data or a variable make sure you use data.d for some reason when using jquery/ajax microsoft wants the .d at the end of the variable. This took me time to figure out.
Try this Im guessing when you debug the deleteUser Method never gets called.
var jqxhr = $.get("admin/manage-users.aspx/deleteUser", { userName: userName } function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
Related
I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});
So having a bit trouble figuring out how to successfully use AJAX to call a method and retrieve data. I am being asked to do this, not exactly sure why but I would usually just handle all this stuff in a MVC environment in the Controller. But for now I am asked to do this in AJAX. I have a ASPX file that I am simply trying to see work so i can move on. So far none of the stack overflow suggestions helped.
Here's what I currently have:
.ASPX/source
<script type="text/javascript">
$(document).ready(function () {
$("#go").click(function () {
$.ajax({
type: "GET",
url: "Default.aspx/ItemData",
processData: true,
data: {},
dataType: "json",
success: function () { alert("yay") },
error: function () { alert("nay") }
});
});
});
</script>
And then in my Default.aspx.cs file I have a method 'ItemData'
[WebMethod]
public static NextCrew.Models.Item ItemData(string cookieID)
{
Item item = new Item();
item.name = "Fred";
item.idx = 1;
item.completed = 1;
return item;
}
(Item is simple a Model withg 3 properties: Name(string), idx(int) and completed(int) )
I am having a hard time figuring out what I am doing wrong here. Can someone please write an example of what I am trying to do? Just a simple GET request that I can return an object (once I get done testing I want to be able to connect to a DB so I need it to be an object) using AJAX.
I can't tell what I am doing wrong but I have some ideas:
1)maybe my url in the ajax isn't formatted properly?
2)do i need to pass anything into data if I have a parameter?
3)is my get method in the correct .cs file?
UPDATE
I was informed I need to have a special class to handle this. I tried to then make a .asmx and the AJAX is still not being called. Hoping someone sees an error that I missed.
<script>
$(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService2.asmx/GetItems",
data: "{}",
dataType: 'Json',
success: function (result) {
// alert(result.d);
$.each(result.d, function (index, ele) {
$("#Myddl").append("<option value='" + ele.value + "'>" + ele.text + "</option>");
})
}
});
})
</script>
.asmx
public class WebService2 : System.Web.Services.WebService
{
[WebMethod]
public List<Item2> GetItems()
{
//suppose data comes from database
var result = new List<Item2>() {
new Item2{ text="one",value="one"},
new Item2{ text="two",value="two"},
new Item2{ text="three",value="three"}
};
return result;
}
public class Item2
{
public string text { get; set; }
public string value { get; set; }
}
}
I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.
Hello I'm trying to run a webmethod with ajax from an aspx page. basically I want to redirect to another aspx page with a query string, but I want to do it from <a href>, beacuse it's part of a jquery menu.
from what I learned I can only use ajax to call static webmethods, but I canot redirect from my static function.
visual studio marks it in a red line saying: "an object reference is required for the nonstatic field method or property System.Web.HttpResponse.Redirect(string)"
here is the ajax call:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
alert("success");
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
here is the a href:
<a onclick="redirect_to_profile()">Personal Profile</a>
here is the webmethod inside the personal_profile.aspx
[WebMethod]
public static void redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
HttpResponse.Redirect("personal_profile.aspx?id="+id);
}
You will need to return the constructed URL to the client:
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
return "personal_profile.aspx?id="+id;
}
Then using JavaScript, in the success function of the AJAX call, set the location:
window.location = res;
Or perhaps:
window.location = res.d;
You need to have your web method pass back the ID of the user whose profile you want to redirect to, then in your jQuery success callback set the window.location to the path plus the query string, like this:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
// Redirect to personal_profile.aspx passing it the ID we got back from the web method call
window.location = "personal_profile.aspx?id=" + res;
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
[WebMethod]
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
return db.return_id_by_user(user);
}
Instead of doing HttpResponse.Redirect you can send this url that you have generated to you Javascript (response to the ajax call) and then use Javascript code to redirect.
Try this:
function myFun(a) {
var s = null;
var em = document.getElementById(a + 'productno');
if (em != null)
PageMethods.setSession(em.innerText);
window.location.assign("/Product%20Details.aspx");
}
I know there are a few questions out there but I've tried a lot of them and I'm still not able to even get my script to make it to the server. Here is what I currently have:
Javascript
function UpdateSessionUser(user)
{
if (user != null)
{
var targetPage = "http://" + document.location.host + "/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser";
var dataText = { "jsonUser" : JSON.stringify(user) };
try
{
$.ajax({
type: "POST",
url: targetPage,
data: dataText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
catch (err)
{
alert(err);
}
}
}
Example of user object
Object
BaseID: "fe85149c-71f2-4c61-b7c6-a00300e2f84e"
HasChanged: true
IsReferralReceived: false
IsReferralRequired: true
IsSeatApproved: true
Name: "Miles"
ReferralFromUser: null
ReferralFromUserID: null
ReferralReceivedBy: null
ReferralReceivedByUserID: null
ReferralReceivedOn: "/Date(-62135578800000)/"
RegisteredOn: "1330281960000"
SeatApprovedBy: null
SeatApprovedByUserID: null
SeatApprovedOn: "/Date(-62135578800000)/"
SeatNumber: "2"
SessionID: "d0773d5e-aeeb-4b9c-b606-0a564d6c5845"
UserID: "6af2fd9e-b4b6-4f5a-8e9c-fe7ec154d4e5"
__type: "SandboxClassRegistration.SessionUserField.ClientSessionUser"
C#
[WebMethod]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
Why does my JSON call never make it to the server? I've put a break point at the very beginning of the function (before the return) just so I can look at the jsonUser object parameter but it never makes it there.
All I get in return is this error:
POST http://localhost:60877/Sitefinity/Services/Sandbox/SessionUsers.asmx/UpdateSessionUser 500 (Internal Server Error)
--- UPDATE
Here is the final result (I had to "stringify" the object and then the final dataText being sent). The webservice method was unchanged
function CallWebServiceToUpdateSessionUser(target, user)
{
var dataText = { "jsonUser": JSON.stringify(user) };
$.ajax({
type: "POST",
url: target,
data: JSON.stringify(dataText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
return true;
},
failure: function (msg)
{
alert(msg);
return false;
}
});
}
I don't how much would help:
try change this
var dataText = { "jsonUser" : JSON.stringify(user) };
to
var dataText = JSON.stringify({ "jsonUser" : user });
I think you need to mark your service method as JASON enabled.
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public bool UpdateSessionUser(object jsonUser)
{
return SessionUserHelper.UpdateSessionUser(new ClientSessionUser(jsonUser));
}
I realize this question was answered a while ago, but I had similar problem, and would like to provide some details on why OP's solution works
I assume the web service expects a string, which it will Deserialize and work with
In this case, calling JSON.stringify({"jsonUser": user}) does not convert user object to string, which will cause problems on the server.
When you call JSON.stringify({"jsonUser": JSON.stringify(user)}), your user oblect is converted to string with all quotes properly escaped.
Hope this helps someone in the future.
Here's the fiddle to illustrate http://jsfiddle.net/dvwCg/2/ :
HTML
<h1>webservice breaks</h1>
<span id="s1"></span>
<h1>webservice works</h1>
<span id="s2"></span>
JS
var jsonObject = {"a":1, "b":[{"x":"test", "y":12}, {"x":"test2", "y":120}]};
$("#s1").text(JSON.stringify({"d" : jsonObject}));
$("#s2").text(JSON.stringify({"d" : JSON.stringify(jsonObject)}));
p.s.
https://stackoverflow.com/a/6323528/3661 has a lot of useful info as well.