Ok, this is my problem :).
I have couple of [WebMethods] in my code behind and using jquery ajax to get data from server.
And then it happens :). After some time while page is inactive when i try to click on button which should have send request to server it simply does nothing for about half of minute and only then event is fired and i get response from server.
my javascript looks something like this:
addToCart.click(function () {
AddOrRemoveItemToCart($(this));
});
function AddOrRemoveItemToCart(control)
{
var itemId = contol.attr("id");
$('document').ready(function () {
$.ajax({
type: "POST",
url: "Home.aspx/AddOrRemoveItemToCart",
data: "{itemId:" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
SucessAddItemToCart(data.d);
}
},
error: function (textStatus) {
alert(textStatus);
}
});
});
}
function SucessAddItemToCart(data)
{
//DO SOMETHING WITH DATA
}
And my server side code look something like:
[WebMethod]
public static List<CartItem> AddOrRemoveItemToCart(string itemId)
{
List<CartItem> items = new List<CartItem>();
List<CartItem>temp = new List<CartItem>();
bool check = false;
if(HttpContext.Current.Session["items"]!=null)
{
items = (List<CartItem>)HttpContext.Current.Session["items"];
foreach(CartItem c in items)
{
if(c.Id != itemId)
temp.Add(c);
else
check = true;
}
if(!check)
temp.Add(new CartItem{Id = itemId});
}
HttpContext.Current.Session["items"]=temp;
return temp;
}
Normally I would have said your Session expired. But since the event fires after half a minute, it has to be something else.
Try to debug with Firebug and check if AddOrRemoveItemToCart gets called immediately. You can also see the traffic between the browser and the server.
Your event should fire immediately but as Remy said your Session has probably expired, and it takes some time to re-establish the session object and process the request.
Related
I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.
Can anyone tell me about how to poll to webMethod on specific interval using Javascript/JQuery ? I tried setInterval & setTimeOut but non of them is working for me. My application generates reports on user's request. since the report generation is taking 10-15 minutes I dont want to block UI thread so I create a reportID on button click from javascript and using _dopostback to call button click event and pass the reportID to it. C# button click event calls generate_report() function using Delegate/BeginInvoke and now I want to poll to WebMethod I have created inorder to get the report... here is a code snippet..
$("#btn1").click(function () {
var ReportID = generateReportID();
__doPostBack("<%= btnGenerate.UniqueID %>", ReportID);
IntervalID = setInterval(function () { Poll(ReportID); }, 30000);
});
function Poll(id) {
$.ajax({
type: "POST",
url: "Default.aspx/WebMethod",
data: "{'ReportID','" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Check if report is ready
// If not poll again after 30 secs
// If report is ready Get the Report and clearInterval
},
failure: function (error) {
}
});
};
[WebMethod]
public static string WebMethod(string ReportID)
{
if (ResultSet.ContainsKey(int.Parse(ReportID)))
{
return "Ready";
}
else
{
return "NotReady";
}
}
So On button click how do I start poll to this web method after every 30 secs till report is "Ready" and clear the interval after once its ready. ??
SetInterval was working fine, PostBack was the culprit.... subsequent postbacks i.e. button clicks would kill the previous setintervals.... so now I pass all the ReportIDs to codebehind on button click function and setIntevals using client script
Page.ClientScript.RegisterStartupScript(typeof(Page), "test" + UniqueID, "setInterval(function () { Poll(ReportID); }, 30000);", true);
alternative to send ReportIDs to code behind functions and looping through and setting interval foreach ReportIDs using client script, one can also save ReportIDs in localStorage so that its available in subsequent postbacks.
NOTE : Thanks a tonn for your help #Krzysztof Safjanowski
Use SetTimeout to call itself recursively, until you have the result you want.
Ex:
function initPoll()
{
setTimeout(pollWebServer(), 30000);
}
function pollWebServer()
{
if(!checkResult())
setTimeout(pollWebServer(), 30000);
}
function checkResult()
{
//Do some work to check result that you are looking for
//This is where you would check your Web Method using jQuery
return false;
}
The code below is triggered on a click of a button and having followed the request through, it is only being triggered once. Also, having stepped through, the code is only triggered once, however, the alerts show twice. Any suggestions for why?
$.ajax({
url: '#ConfigurationManager.AppSettings["AppDirectory"]/OperatorApplication/PafSearch/' + pafPostcode.val(),
type: 'POST',
success: function (response) {
addressList.empty();
addressSelection.hide();
if (response == null) {
alert("No addresses found for the postcode provided.\n\nPlease enter your address manually");
}
//other processes removed...
}
});
How did you bind the click event to the button? Or did you bind the same event multiple times?
Is it like this:
$("#targetButton").on("click", function(){
$.ajax({
url: '#ConfigurationManager.AppSettings["AppDirectory"]/OperatorApplication/PafSearch/' + pafPostcode.val(),
type: 'POST',
success: function (response) {
addressList.empty();
addressSelection.hide();
if (response == null) {
alert("No addresses found for the postcode provided.\n\nPlease enter your address manually");
}
//other processes removed...
}
});
return false;
})
I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}
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"); });