Prevent ajax post when back button is pressed - c#

When the form is posted(ajax), I am navigating to other page and while pressing the back button, the form is again posted.
Is there any way to stop ajax post while clicking on back button in browser ?
I have used the below code to stop previous request, but after this back and forward button are disabled in the browser.
window.onpopstate = function (e) {}; history.pushState({}, '');
NOTE: I am getting this issue only in chrome and safari.

As this answer suggest suppose you have this ajax request
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg) {
alert("Data Saved: " + msg);
}
});
window.onpopstate = function(e) {
//kill the request
xhr.abort()
};
history.pushState({}, '');

Related

from contact form to sendemail MVC5

Im having some contact form and I have in a HomeController method SendMessage, also in my form I have hidden success and error div.
How to call sendmessage, but to stay on the same page?
As commented by Igor, use an ajax call to hit your controller/method.
Here is an example -
<script>
$(function () {
$('#sendMail').click(function () {
$("#sendMail").empty();
$("#sendMail").attr("disabled", true);
$("#sendMail").append('<i class="fa fa-spinner fa-spin"></i>Please wait...');
$.ajax
({
url: '#Url.Action("SendMail", "ControllerName")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ 'name': $('#txtName').val(), 'email': $('#txtEmail').val(), 'message': $('#txtMessage').val() }),
success: function (result) {
$("#sendMail").empty();
$("#sendMail").append('Send Message');
$("#sendMail").attr("disabled", false);
},
error: function (result) {
$("#sendMail").empty();
$("#sendMail").append('Send Message');
$("#sendMail").attr("disabled", false);
}
});
})
})
</script>
In above javascript function -
When user clicks on button with text 'Send Mail' and id = sendMail, I disabled the button so the user won't click it multiple times and change the text of button to 'Please wait' and add a spinner for dramatic effect. I also send email of the user and name and message with the ajax call. On ajax success, I show a toaster with success message and remove the spinner and please wait text from the button and set 'Send Mail' text again.
I removed toaster javascript part in case you want to use other notification method. Good luck.

Submit form through ajax and callback an alert

I submit a form using ajax request. The form is actually inside a modal popup. The submission works well. But I want it to show an alert that said the form is submitted and close the current modal. Here is my code:
$('#btnBookRoom').click(function() {
$.ajax({
url: "/Booking/BookRoom",
type: "POST",
data: $('#frmRoomBooking').serialize(),
datatype: "json",
sucess: function(data) {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
}
});
});
Controller:
public ActionResult BookRoom(RoomBookingInputModel roomBooking)
{
var domain = new RoomBooking
{
GuestId = roomBooking.GuestId
};
db.RoomBookings.Add(domain);
db.SaveChanges();
return Json(domain, JsonRequestBehavior.AllowGet);
}
The alert doest shows and the modal also not hiding.
sucess isn't a valid callback in jQuery's ajax method. You need to change it to success.
Or better, use promise API to bind a success handler (as AJAX callbacks are already deprecated):
$.ajax({ ... })
.then(function() {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
});

How to poll to WebMethod using Jquery/Javascript

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;
}

how can i prevent code behind method call in asp.net

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();
}

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Categories