In my application I have used jquery ajax and this ajax call invokes some method at server side. In this method I have code which grabs the query strings and based on the query string value it processes the data. I am using below lines of code to get query string.
var MyajaxCall = function () {
$.ajax(
{
type: "POST",
url: "OneCol.aspx/SingleData",
data: JSON.stringify({DptID:1}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
jsonData = msg.d;
},
Error: function (x, e) {
alert("Some error");
}
});
};
C# code
[WebMethod]
public static string SingleData(string DptID)
{
OneTestPage onpage = new OneTestPage ();
return onpage.GetString();
}
private string GetString()
{
return Request.QueryString["test"].ToString();
}
Everytime my ajax request hits this line of code I am getting "Request is not available in this context". Is this because data is not ready yet this time ? if so what is the best way to get it work.
Related
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
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'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"); });
I have the following Webmethod in my C#/.NET web-application, file lite_host.aspx.cs:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result;
}
It should get the values of "accessCode" and "newURL" from a JavaScript function via a jQuery AJAX call with and make the appropriate changes in Cache:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However when I call the sendUpdate() function, I my script ends on $.ajax error and I'm getting an alert text "undefined".
Undefined means that msg.d doesn't exist. Try doing a console.log(msg) and use Chrome's debugger to see what is outputted (yeah, I know) to the console.