Display confirmation message before send ajax request - javascript

I have written an ajax function where I want to display confirmation meeessage before submitting the form. How should I add with my condition. Below is my code.
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
}
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
})
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}

The solution is to use beforeSend ajax property.
beforeSend is a pre-request callback function before it is
sent.Returning false in the beforeSend function will cancel the
request.
beforeSend:function(){
return confirm("Are you sure?");
},
AJAX
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});

Use ajax beforeSend callback function.
beforeSend: function () {
if(confirm("Are you sure?")){
// do something
} else {
// stop the ajax call
return false;
}
},
See documentation Ajax http://api.jquery.com/jquery.ajax/

Write your ajax into a function like:
function save(){
// something in here
}
After that write a confirmation functionality, if user confirm then call save() function

Maybe this exemple is what you need ?
var r = confirm("Press a button!");
if (r == true) {
// Make your ajax call here
} else {
// He refused the confirmation
}
Call your confirm before ajax call ?

You can try to put your confirmation message in the beforeSend method : http://api.jquery.com/jquery.ajax/

if ( confirm("Do you want to Submit?")) {
// If you pressed OK!";
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});
} else {
// If you pressed Cancel!";
}
Please check with window.confirm

I ran into this issue recently, so this is my answer, I am using jquery and jqueryconfirm, the "beforesend" callbak only allows the standard "alert" and "confirm" functions.
What I did is placing a "fake" submit button and hide the actual submit one, so it was easy dealing with the response from the custom confirm dialogs, once I got the affirmative answer from the dialog I call the "click" method of the hidden submit button.
...
<button id="confirmSave" type="button">Save</button>
<button id="save" class="is-hidden" type="submit"></button>
<button id="close" aria-label="close" type="reset">Cancel</button>
...

Related

Add confirm (yes no) in submit with preventDefault

i have code submit with preventDefault. this my code
//submit terima barang
$("form.form_terima").submit(function (event) {
if (confirm('Submit Terima Barang ?')) {
$(".loader").show();
//disable tombol submit supaya tidak reload
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'po_req/po_req_crud.php', //type='add_terima'
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
//action if success
}
});
return false;
}
});
but, it's not working. how to solve it ? thanks buddy :)
In your code, the event.preventDefault() will run only when the user has clicked "OK"/"Yes". If the user has clicked "No", then the form will submit.
You must add the event.preventDefault() outside of the if block to make it work as you expect.
$("form.form_terima").submit(function (event) {
if (confirm('Submit Terima Barang ?')) {
$(".loader").show();
//disable tombol submit supaya tidak reload
var formData = new FormData($(this)[0]);
$.ajax({
url: 'po_req/po_req_crud.php', //type='add_terima'
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
//action if success
}
});
}
// prevent default regardless of user's response
event.preventDefault();
return false;
});

jquery $.when.done() is not firing

I'm not sure if I am using the $.when correctly but this is what I am trying to do. I am trying to fire two ajax calls and when they both complete, I need to perform some additional work, however, my .done method never fires. My alert box is never hit, however, both of my Ajax requests are being executed.
The alert "DO NOT HIT HERE" gets triggered. I would like to prevent that from happening. I need it to trigger within the .done only.
function ValidateGeneralTab() {
var isValid = false;
$.when(SetGeneralTabIsValid(isValid), PostErrorMessages()).done(function ()
{
alert("Im here");
return isValid;
});
alert("DO NOT HIT HERE");
}
function SetGeneralTabIsValid(isValid)
{
var request = $.ajax({
type: "POST",
url: "NewIRA.aspx/SetGeneralTabIsValid",
data: "{'isValid': '" + isValid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function () {
}
});
return request;
}
function PostErrorMessages() {
var errorsCollection = ["Saab", "Volvo", "BMW"];
var request = $.ajax({
type: "POST",
url: ErrorMessagesUrl,
data: JSON.stringify(errorsCollection),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function () {
}
});
return request;
}

How to create the confirm box (modal popup) in asp.net MVC?

How to create the confirm box (modal popup) after i click this button:
<button id="sellButton" onclick="sendRequest(#item.Id)">Sell</button>
HERE POPUP MODAL (YES/NO)
When user will confirm, then this should happen
<script>
function sendRequest(id)
{
var request =
{
"itemId": id
};
$.ajax({
url: '/It/Sell',
data: JSON.stringify(request),
type: 'POST',
dataType: "html",
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
$('#Table').html(result);
},
async: true,
processData: false
});
};
</script>
if(confirm('are you sure?')){
var request =
{
"itemId": id
};
$.ajax({
url: '/It/Sell',
data: JSON.stringify(request),
type: 'POST',
dataType: "html",
contentType: 'application/json; charset=utf-8',
error: function (err) {
alert('Error: ' + err.statusText);
},
success: function (result) {
$('#Table').html(result);
},
async: true,
processData: false
});
}
Have look at jquery.confirm. It should be able to solve your problem.
If you want to have nice modal confirm box with simple implementation i would recommend Bootstrap3 Dialog
Import necessary files to your project. And
function sendRequest(id)
{
BootstrapDialog.confirm('Are you sure you want to continue?', function(result){
if(result) {
//Send Ajax Request
}
});
}
More Info : https://nakupanda.github.io/bootstrap3-dialog/

Is it possible to send entire form including the files to server using jquery/ajax?

Is it possible to submit entire form (all the fields including fileupload) to server (webmethod or handler etc) using Jquery/Ajax? If yes, how?
ASPX:
$.ajax({
type: "POST",
url: "SupplierBidding.aspx/SubmitBid",
data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
span.fadeIn("slow", function () {
span.text(data.d).fadeOut('slow');
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
setTimeout(function () {
btn.prop('disabled', false);
}, 3000);
}
});
}
WebMethod:
[WebMethod]
public static string SubmitBid(string id, string bidamt)
{
//code
return "";
}
I would like to replace data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }) with entire form including files also.
You can use Formdata.
FormData Docs
Code example.
var fdata = new FormData();
fdata.append( 'file', input.files[0] );
$.ajax({
url: 'http://yourserver.com/upload.php',
data: fdata,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log('siceess')
}
});
Did you try jQuery Form plugin?
It handles file uploads.
Worked for me before.

Redirect to another page does not work in ajax call

I have written one ajax post request on aspx page which will call web method written in its code behind class.This method return url to redirect..All is working fine till success function of ajax call but in success function I'm redirecting to another page ex.
window.location.assign(data.d)
I have checked data.d result via alert in success function which is showing correct url but its not rediecting to that page..Plz help..
Full code is here..
This is script:
<script type="text/javascript">
jQuery(document).ready(function() {
$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type: "POST",
url: "testAjax.aspx/Authenticate",
data: JSON.stringify({ userName: userName, password: password }),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { window.location.assign(data.d); },
error: function(e) {
alert(e.valueOf());
}
});
//alert("dsf");
});
});
</script>
and following is the web method:
[WebMethod]
public static string Authenticate(string userName, string password)
{
try
{
return "Home.aspx";
}
catch (Exception ex)
{
return string.Empty;
}
}
Please note: If I uncomment alert("dsf"),all works fine it redirects successfully to Home.aspx..But without this alert it wont redirect.
try this
success: function(data) { window.location=data.ToString(); }
Try this
<script type="text/javascript">
jQuery(document).ready(function() {
$('#loginbtn').click(function() {
var userName = document.getElementById('uid').value;
var password = document.getElementById('pwd').value;
$.ajax({
type: "POST",
url: "testAjax.aspx/Authenticate",
data: JSON.stringify({ userName: userName, password: password }),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { window.location=data.d; },
error: function(e) {
alert(e.valueOf());
}
});
//alert("dsf");
});
});
</script>

Categories

Resources