ajax call is not working for the c# method - c#

i want to call the unlock method on closing or redirecting other page, so i have used ajax call. but the method unlock is not firing. please let me know what i am doing
[WebMethod]
public void Unlock()
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;

Where you passing project_id in your ajax call???
pass project_id in your method
[WebMethod]
public void Unlock(string project_id)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
and then rewrite ajax call as
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
data : "{project_id:'1234'}",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;

There's a couple of issues. Firstly your WebMethod expects a querystring parameter, yet you're sending a POST request and you also don't send any data in the request. You should provide project_id as a parameter in an object to the data property of the AJAX request.
Also note that sending an AJAX request in the onbeforeunload event is one of the very few legitimate cases where you need to use async: false to stop the page from being closed before the AJAX request completes. Try this:
[WebMethod]
public void Unlock(string projectId)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(projectId), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
async: false, // only due to running the code in onbeforeunload. Never us it otherwise!
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { projectId: '1234' }
});
}
window.onbeforeunload = HandleOnclose;
Also note that depending on the browser you may be restricted from sending an AJAX request in the onbeforeunload event at all. See this question for more details.

Related

FileUpload formData in ASP.NET WebForms

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.

Error with my Ajax post with jQuery

I am trying to post to a method using jQuery and Ajax. My Ajax code is as follows:
var isMale = $(e.currentTarget).index() == 0 ? true : false;
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: { isMale: isMale },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
And here is my WebMethod:
[WebMethod]
public static void SetUpSession(bool isMale)
{
// Do stuff
}
I get a 500 (Internal Server Error) looking at the console, the method never get's hit. After I changed data to "{}" and removed the bool from the method signature the method then gets hit, so I'm assuming its something to do with the Ajax.data attribute I'm trying to pass.
Two things you need to modify :-
1) Make sure that this line is written in your web service page and should be uncommented.
[System.Web.Script.Services.ScriptService]
2) Modify the "data" in the code as :-
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: '{ isMale:"' + isMale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
Pass string instead of bool
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}
Alternative you can use pagemethods through script manager.
Try following code:
var params = '{"isMale":"' + $(e.currentTarget).index() == 0 ? true : false + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
responseType: "json",
success: function (data) {}
});
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}

Ajax JQuery Passing Data to POST method

I am a newbie at javascript and jquery and I would like some help if possible. I searched and tried to make it work, but I think I am missing something simple.
I have the following method in my cs file (CeduleGlobale.aspx.cs)
[WebMethod]
public static void SetSession(string data)
{
HttpContext.Current.Session["salesorderno"] = data;
}
I also have a some javascript in my ascx file
<script type="text/javascript">
function SetSession() {
var request;
var values = 'fred';
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
request.done(function () {
alert("Finally it worked!");
});
request.fail(function () {
alert("Sadly it didn't worked!");
});
}
</script>
The function in the script is called by
<dx:ASPxCheckBox ID="cbxHold" runat="server" AutoPostBack="true" Text="OnHold" ClientSideEvents-CheckedChanged="SetSession">
</dx:ASPxCheckBox>
And the result i keep getting is "Sadly, it didn't work!".
I know the problem is not with anything relative to the path of the url, because it worked when i passed NULL as data and had the method with no parameters.
The parameters and data is what i tripping me I believe.
You should pass serialized JSON into the method:
var values = JSON.stringify({data:'fred'});
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
You are specifying that you are sending JSON, but you don't serialize the value to JSON, so try changing the request to this:
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: JSON.stringify({data: values}), // 'stringify' the values to JSON
contentType: "application/json; charset=utf-8",
dataType: "json"
});
'fred' is not json nor object
use object notation :
{"myattr":"fred"} //you can also do {myattr:"fred"}
and then use JSON.stringify which transform it into STRING representation of json object.
The data sent through post should be sent in a {key:value} format
values={name:'fred'}
The data should be passed into [key:value] pair.

asp.net call WebMethod from Javascript asyncronous

I am trying to build an asp.net(c#) page that updates some state texts every second.
Now I have implemented an button that calls another PageMethod which restarts something and takes a little while. The problem is, that when I call the restart PageMethod , the update PageMethod can't update as long as the restart method is proceeding...
I wrote a little example to show what I mean:
WebMethods in my Page:
[WebMethod]
public static string Update()
{
//return "a" to see when the Update PageMethod succeeded
return "a";
}
[WebMethod]
public static string Restart()
{
//the restart will take a while
Thread.Sleep(2000);
//return "a" to see when the Restart PageMethod succeeded
return "a";
}
the html elements to update:
<p id="update" style="float:left;"></p>
<p id="restart" style="float:right;"></p>
the Pagemethod calls:
callUpdate()
function callUpdate() {
PageMethods.Update(function (text) {
//itself+text from pagemethod
$('#update').text($('#update').text() + text);
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
PageMethods.Restart(function (text) {
//itself+text from pagemethod
$('#restart').text($('#restart').text() + text);
});
setTimeout(callRestart, 1000);
}
Note: The Update is also called every second after it finished, just to see how it works
To clarify: I want the PageMethods to execute independent to that the other PageMethod has finished.
I also flew over some links like:
http://esskar.wordpress.com/2009/06/30/implementing-iasyncresult-aka-namedpipeclientstream-beginconnect/
http://msdn.microsoft.com/en-us/library/aa480516.aspx
But I don't think this is what I need (?)
And I really don't know how to call that from Javascript (BeginXXX and Endxxx)
*EDIT: *
Regarding to Massimiliano Peluso, the js code would look like this:
callUpdate()
function callUpdate() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Update",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#update').text($('#update').text() + msg.d);
}
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Restart",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#restart').text($('#restart').text() + msg.d);
}
});
setTimeout(callRestart, 1000);
}
Note: when I run the Page with the new js, there is exactly the same problem as before: The Update method can do nothing until the Restart method is finished.
you should call the page methods using an Async call instead.
have a look at the below. It is a generic way to call a page method using JQuery
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
you should use this code to replace the page method calls
PageMethods.Restart(function (text))
PageMethods.Update(function (text))
It's because an Request only Proceeds when no other Request is processing.
Thats because two Processes can't acess to the same SessionState (Sessionstate is not Threadsafe).
So to achieve that Requests are processed at the same time, you have to set EnableSessionState in the #Page directive to either 'ReadOnly' or 'false'

jQuery Ajax passing the Form Collection

I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?
You can do something like this:
var form = $("#myForm").serialize();
$.post("/Home/MyUrl", form, function(returnHtml)
{
//callback
});
Then on the C# side you should be able to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyUrl(FormCollection collection)
{
//do what you gotta do
}
I think this should work.
EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.
You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.
Got this working all okay, and it returns the input form collection in the FormCollection
input = $(':input')
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: input,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});

Categories

Resources