I use this jquery to show my popup,
//ResetPassword Popup display
$(document).ready(function () {
var passwordExpiredVal = $("#isPasswordExpired").html();
if (passwordExpiredVal == "True") {
$("#ResetPasswordModal").modal({
show: 'true'
});
};
});
I use this jquery to pass the new typed password to controller action ON CLICK, once the save button is clicked I want the popup to close
//Reset Password submit
$(document).ready(function () {
$("#submitSave").on("click", function () {
var confirmPassword = $("#txtLgnPasswordConfirmReset").val();
var passwordReset = {
UserName: $("#txtLgnUsername").val(),
Password: $("#hdnOldPassword").val(),
NewPassword: $("#txtLgnPasswordReset").val()
}
if (passwordReset.NewPassword != confirmPassword) {
notifyMessage.showNotifyMessage('error', 'The passwords entered should match', false);
$("#txtLgnPasswordReset").val("");
$("#txtLgnPasswordConfirmReset").val("");
}
else {
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset,
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
error: function () {
alert('failure');
}
});
}
});
});
My jquery function is not helping...
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
Any ideas??
Thanks in advance...
The code you are using is unnecessarily initializing the modal again on that element.
Use modal('hide') : Docs,
success: function () {
$('#ResetPasswordModal').modal('hide');
},
If you further wish to use this again, 'toggle' would be a better option.
$('#ResetPasswordModal').modal('toggle')
Related
I would like to merge two JavaScripts. The first one is using ajax to send message and the second one to alert user about required field in the contact form.
I want to merge this two, maybe with an IF statement, so first to check all fields and then to send message.
1 with ajax JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
2 alert JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
From the answer below i have create the following code.
I made this link if someone wants to help. The alert works fine but the code not stop. It continue to load the rest code.
https://jsfiddle.net/L8huq1t1/
You can do this by the following code.
function checkValidation() {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
//e.preventDefault();
return false;
}
});
return true;
}
$('document').ready(function () {
$('form#contact-form').submit(function () {
if(!checkValidation()) {
return false;
}
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
But I give you a suggestion to use jquery.validate plugin which is better option. But if you still want to do like this, go ahead this is also works fine.
You can use jQuery Validation plugin that has a form submit handler where you can put your AJAX. Link to the plugin.
Your code should look something like this:
$('#contact-form').validate({
rules: {
your_input_name: {
required: true
}
},
messages: {
your_input_name: {
required: 'Field is required'
}
},
submitHandler: function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function() {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
return false;
}
});
HTML5 validation isn't working in Safari so I'm using Happy.js.
My form is still submitting via ajax in Safari though with the code below (here is JSFiddle).
How can I validate #email-input before sending the form with ajax?
The code below is checking if ($(this).hasClass('unhappy')) then don't submit form, if it doesn't have class unhappy then submit form. But I guess the problem is that it doesn't have class unhappy from the beginning.
used from this reference: isHappy.js allowing ajax call when not valid
$(document).ready(function() {
function ajaxEmailForm() {
$(".sendingEmailLink, .sentEmailLink").hide();
$('#email-form').submit(function(event) {
event.preventDefault();
var formserialize = $(this).serialize();
var submitButton = $('#submitEmailForm');
$.ajax({
type: 'POST',
url: 'https://formkeep.com/f/MYID',
accept: {
javascript: 'application/javascript'
},
data: formserialize,
beforeSend: function() {
$(".sendEmailLink").hide();
$('.sendingEmailLink').show();
},
complete: function() {
$(".sendingEmailLink").hide();
},
success: function(d) {
$('.sentEmailLink').show();
},
error: function() {
$('.notification-e--phone').slideDown("medium", function() {});
},
}).done(function(data) {
submitButton.prop('disabled', 'disabled');
});
});
};
$('#email-form').isHappy({
fields: {
'#email-input': {
required: true,
test: happy.email,
message: 'Please enter your full email address.',
errorTarget: '.email-input-error'
}
}
});
var is_unhappy = false;
$('#email-form div :input').each(function(i) {
if ($(this).hasClass('unhappy')) {
is_unhappy = true;
return false;
}
});
if (!is_unhappy) {
ajaxEmailForm();
};
});
I have the following js code:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
When I click the button with the id add_station it alerts on click function after $($this).closest('form').submit(function(){...) it doesn't work as you can see I've put an alert 'works' after submit function.I get no errors on the console and I can't figure what the problem is. Also, the button that is clicked is inside a form.
I need to use $($this).closest('form').submit(function(){...) inside because after ajax success a new form will be generated with add station button that will use this code.
You should block the default submit trigger by using
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
add a separately submit handler
$("#add_station").on('click', function () {
$(this).closest('form').submit();
});
$("form").on("submit", function (e) {
e.preventDefault();
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
after ajax success a new form will be generated with add station
button that will use this code
If you generate a new button you have to bind the click again after it is placed to the dom.
I have an MVC4 application, and on the layout (master page for the oldies), I have some javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
This simply logs in a user.
This is working fine.
However, on another screen I now have some new javascript, which does similar function, by taking data from a form, and passing it to a controller to handle.
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').on('click', function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
// window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
When I click the save button that this code is linked to, the code fires, the controller method goes well, the data is stored, but then, when I refresh the screen, I get an 'Undefinied' error coming from the LOGIN script above. It seems to fire when the page is reloaded. I am unsure why it's firing. It should just load, ready to fire, but it seems to be called, and fails.
The controller that it calls is this:
public ActionResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(expiryYear, expiryMonth, 1)
};
int id = new BankAccountService().SaveCard(card);
return RedirectToAction("EditBankAccount", new { bankAccountId = accountId });
}
The problem happens on the RedirectToAction... when that view reloads, which includes the Layout, the Layout javascript fires.
EDIT: I now see that it's the btnSubmitNewCard javascript that is fired twice. Once when the click event happens (expected), and then again when the postback happens. Why is the second event happening?
Check with this: -
$('.btnSubmitNewCard').click(function () {...});
You are getting Undefined in the line that checks status:
if (result.Success == 'true') {
Because result contains string with html response of the view for the EditBankAccount action and does not have "Success" property.
You can put breakepoint in debugger and see. You can use debugger; statement as breakpoint
I need to request additional credentials to a user when he clicks certain buttons and submits certain forms.
I way I am trying to do it is:
Intercept the submit event, abort it, and store a copy
Ask for the credentials with an prompt dialog (not the JS native one, so this is all non-blocking)
If user inputs the credentials, insert the fields into the event data and send it to the server.
My current code for AJAX requests is:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if (ajaxOptions.type === "POST") {
$.current_request = jqXHR;
jqXHR.abort();
$.check_password_with_my_dialog();
}
});
$.check_password_with_my_dialog: function() {
$("#validate-password-prompt").dialog({
modal: true,
title: "input pw",
buttons: {
Ok: function() {
$.password = $("#validate-password-prompt input").val();
$.deliver_current_request();
return $(this).dialog("close");
},
Cancel: function() {
return $(this).dialog("close");
}
}
});
}
deliver_current_request: function() {
$.current_request.beforeSend = function(jqXHR, ajaxOptions) {
ajaxOptions.data = ajaxOptions.data.concat("&password=" + $.password);
};
$.ajax($.current_request);
}
The problem so far is that ajaxOptions.data is undefined, so I can't add my data.
And the requests seems to be going as a GET instead of POST.
Am I doing this the right way, or am I way of?
updated
Here is a way i can think of to accomplish answer for your question.
<form id="myForm" >
<button id="submit-form-btn">Submit</button>
</form>
<div id="validate-admin-password-prompt">
<input type="password"/>
</div>
In javascript,
function submitForm(pwd) {
var formData = $('form#myForm').serialize() + "&password=" + pwd;
$.ajax({
type: "POST",
url: "http://google.com",
data: formData,
dataType: "script"
});
alert("POSTed: " + formData.toString());
}
function alertDialog() {
$("#validate-admin-password-prompt").dialog({
modal: true,
title: "Admin password is required",
zIndex: 10000,
buttons: {
Ok: function() {
$(this).dialog("close");
var pwd = $("#validate-admin-password-prompt input").val();
submitForm(pwd);
},
Cancel: function() {
$(this).dialog("close");
alert('Not authorized to submit the form');
return false;
}
}
});
}
$("#submit-form-btn").click(function(e) {
e.preventDefault();
$ele = $("#validate-admin-password-prompt input");
if ($ele.val()==null || $ele.val().trim()=="") {
alertDialog();
} else {
submitForm($ele.val());
}
});