asp.net button client side confirmation before submit - javascript

I have this problem: I need to validate that files have not been uploaded already, for which I use a webservice with Jquery called by isAlreadyUploaded() which returns true or false. Should the files exists, a confirmation to proceed is asked. THEN, once that is finished, I want to call the Button1_Click function to finish the operation. My problem is tha both of them are being called at the same time, thus avoiding the confirmation.
Maybe I am approaching the problem the wrong way. If so, feel free to correct me.
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" OnClientClick="return isAlreadyUploaded()" />
<script>
function isAlreadyUploaded() {
var mystring = "";
$.ajax({
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
});
}
</script>

It should work if you add the following option:
$.ajax({
/* ... code ...*/
async : false,
/* ... code ...*/
});
You're making an asynchronous request to the server when you need to make a synchronous request.
http://api.jquery.com/jQuery.ajax/

Because ajax is async by nature isAlreadyUploaded will not wait for the server to respond and since you are not returning anything from isAlreadyUploaded it will be treated as true and the button will submit the form.
You can set async property of ajax config to false so that it will wait for the server to respond before leaving from the function.
function isAlreadyUploaded() {
var mystring = "", retVal = false;
$.ajax({
async: false
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
retVal = true;
} else {
retVal= false;
}
} else {
retVal = true;
}
}
});
return retVal;
}

There is an ConfirmButtonExtender in the ajax toolkit which might be what you're looking for.
Here is an example i found:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx

Related

Unable to bind data to textbox in ajax success function

[WebMethod]
public static List<SalesInvoiceFinalCalculationEntity> salesInvoiceFinalCalculaiton(string InvoiceNo)
{
List<SalesInvoiceFinalCalculationEntity> list = new List<SalesInvoiceFinalCalculationEntity>();
list = SalesInvoiceManager1.salesInvoiceFinalCalculaiton(InvoiceNo);
return list;
}
Above code returns list of some values which i want to bind to textboxes. I cant understand that why these values are not getting in ajax Success function below:
function salesInvoiceFinalCalculaiton() {
var invoice = {};
var InvoiceNo = $("#txt_InvoiceNo").val();
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AjaxRequestToServer.aspx/salesInvoiceFinalCalculaiton", //URI
data: "{InvoiceNo:'" + InvoiceNo + "'}",
dataType: "json",
success: function (data) {
//Commented code working Fine
//if (!$.trim(data)) {
// alert("What follows is blank: " + data);
//}
//else {
// alert("What follows is not blank: " + data);
//}
//bootbox.alert("Hi", function (e) { });
//But cannot Bind data in textbox
$('#txtinvoicevalue').val(data.d[0].totalprice);
$('#txtTotalDiscount').val(data.d[0].discountamt);
$('#txtGrandTotal').val(data.d[0].grandtotal);
},
error: function (xhr) {
if (xhr.statusText == "Invalid Request") {
sessionStorage.clear();
}
}
});
}
Here Success function working fine. And Commented code also gives right output. But I cant assign the data to textboxes. Thanks in advance.
try using getElementById instead and see if that helps, also check to see if you can print the values into your debug console.
pressing F12 will usually show you the development console on browsers, check your script errors there.

ajax loading indicator stopped in between

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});
The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

ajax post error: internal error 500 on post method

I am running the script below whe a timer has run out of time, the post was working fine when i started passing the data through that is need for the final information is saved. that when got an internal error.
JavaScript ajax call
var selectedval;
if (document.getElementById('RadioButtonList1_0').checked == true) {
selectedval = document.getElementById('RadioButtonList1_0').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_2').checked == true) {
selectedval = document.getElementById('RadioButtonList1_2').value
}
else if (document.getElementById('RadioButtonList1_3').checked == true) {
selectedval = document.getElementById('RadioButtonList1_3').value
}
else {
selectedval = '';
}
var qustNo = document.getElementById('ltlQuestNos').innerHTML;
`enter code here` $.ajax({
type: "GET",
data: '{questNo:'+ qustNo.trim().toString()+',selectedoption:'+ selectedval.toString()+'}',
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function (result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
Vb.net code.
<WebMethod()>
Public Shared Function timeFinished(questNo As String, selectedoption As String) As String
Dim objExam As New examClass()
If selectedoption = "-1" Then
'lblWarning.Visible = True
'lblWarning.Text = "Please answer Question!"
Else
' lblMessage.Text = "Navigation = " & Request.Form("textNav")
objExam.answerQuestion(HttpContext.Current.Session("examid"), questNo, selectedoption, "00:00:00")
' lblWarning.Visible = False
'close connection
objExam.Dispose()
End If
objExam.finishTest(Convert.ToInt32(HttpContext.Current.Session("examid").ToString()))
objExam.Dispose()
' HttpContext.Current.Response.Redirect("ChapterTestSummary.aspx", true);
Dim url As String = "testsummary.aspx"
Return url
End Function
I think the problem is with data part in ajax. Because, if you are building the data as string by yourself, key and value should enclosed in double quotes. Otherwise make it as an object and use JSON.stringify() method to make it as string.
$.ajax({
type: "GET",
data: JSON.stringify({
questNo: qustNo.trim(),
selectedoption: selectedval
}),
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function(result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
});

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Updating jQuery Item during Ajax call

I am making an ajax call to send out a couple of emails when the user clicks a button. I am trying to update a "Please wait..." div before and after the call with the status, as well as report any errors. The problem... is that the div doesn't actually update until the ajax call is complete.
If I comment out the ajax call the status update works fine, but fails if the ajax call takes place. My Windows programming experience tells me the div needs to be refreshed, but I'm not sure how this is done, or if this is the right method.
For example:
$("#msgEmail").show();
$("#msgEmail").html("Preparing to send");
$.ajax({ blah blah blah...
Any pointers in the right direction will be much appreciated!
On nnnnnn's suggestion I started testing on other browsers. The problem occurs on Chrome and Safari, but works as expected on Firefox and SeaMonkey. It sure looks like he's right about this. Now I just need to figure out to implement setTimeout() in this scenario.
Update: Code:
.click(function() {
$('#myTable :checkbox:checked').each(function() {
sId = $(this).attr('cid');
sName = $(this).attr('cname');
ret = true;
$("#msgImage").slideDown();
sUpdate = 'Sending alerts to class: '+ sName;
$("#msgEmail").slideDown();
$("#msgEmail").html(sUpdate);
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData= "cid="+sId+'&sname='+sName+'&subject='+sSubject+'&message='+encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function (msg)
{
if(msg >= '1')
{
ret = true;
}
}
});
if(ret)
$("#msgEmail").html('Finished sending alerts');
$("#msgImage").slideUp();
ret = false;
return false;
})
Place your ajax call in the callback for 'slideDown'. Set the message before calling 'slideDown'. This will ensure your message is updated before the ajax call is sent.'
sUpdate = 'Sending alerts to class: ' + sName;
$("#msgEmail").html(sUpdate);
$("#msgEmail").slideDown(function() {
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData = "cid=" + sId + '&sname=' + sName + '&subject=' + sSubject + '&message=' + encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function(msg) {
if (msg >= '1') {
ret = true;
}
}
});
});
I ll get you an on hw this stuff is going to be
$(document).ready(function(){
$.ajax({
url :'YOur url',
.....
.....
ajaxSend :function(){
$('#yourdiv').html('please wait...');
}
success:function(msg){
if (msg >= '1') {
$('#yourdiv').html('validated');
}
}
});
}):

Categories

Resources