I'm experiencing a problem with my form. Im trying to post data to a PHP file using Ajax, but i stumbled across a problem with form validations.
My Form
<form id="kt_modal_new_target_form" class="form" name="kt_modal_new_target_form" method="post" action="test.php">
....
<button type="submit" id="kt_modal_new_target_submit" class="btn btn-primary">
<span class="indicator-label">Submit</span>
</button>
</form>
Part of my Modal with form hander file (the part which validates the form.) As you see, after it validates the form, the is a form submit function, but i cant seem to make it work as ajax. I've tried $.ajax, I've tried submitting through the html file, but then it doesn't validate the form...
submitButton.addEventListener('click', function (e) {
e.preventDefault();
// Validate form before submit
if (validator) {
validator.validate().then(function (status) {
console.log('validated!');
if (status == 'Valid') {
submitButton.setAttribute('data-kt-indicator', 'on');
// Disable button to avoid multiple click
submitButton.disabled = true;
setTimeout(function() {
submitButton.removeAttribute('data-kt-indicator');
// Enable button
submitButton.disabled = false;
// Show success message. For more info check the plugin's official documentation: https://sweetalert2.github.io/
Swal.fire({
text: "Nurašymas atliktas!",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
}).then(function (result) {
if (result.isConfirmed) {
modal.hide();
}
});
form.submit(); // Submit form
}, 2000);
} else {
// Show error message.
Swal.fire({
text: "Pildant nurašymą rasta klaidų, bandykite dar kartą.",
icon: "error",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
});
}
});
Anyone able to help me out? I need this form to validate through the .js file and then to send the data using Ajax to a PHP file.
Related
I am having a form to get the user details.
Once form is submitted the page gets loaded. I want to display a success message after page loading.
<form name="myForm" class="contactus-template" method="post" onsubmit="return Formvalidation()">
</form>
function Formvalidation(){
var validate = validateForm();
if( validate == true ){
alert("success");
}
else{
alert("not success");
}
return validate;
}
This is script I am using now. This gives alert before page reload. I want to do this after that return function.
Use Bootstrap Notify: http://bootstrap-notify.remabledesigns.com/
And this script:
Alert = {
show: function(type, title, message, url, delay) {
$.notify({
title: title,
message: message,
url: url,
target: "_blank"
},{
type: type,
showProgressbar: false,
placement: {
from: "bottom",
align: "center"
},
delay: delay
});
},
}
Then you can calling a message with PHP if page is reloaded:
echo '<script>Alert.show("success", "", "Form submit success!", "", 3000);</script>';
Have considered redirect user to another page success/failure, and display result in that page?
If you want to call Formvalidation() when the user clicks the submit button, onsubmit="return Formvalidation()" should simply be onsubmit="Formvalidation()".
I'm trying to implement Sweet Alert to Node.js delete form, but unfortunately the alert doesn't work properly. It only pops up for a second and without clicking on delete button on the alert window, it deletes file from DB.
Here is my code:
<form action="/comicbooks/<%= comicbook._id %>/?_method=DELETE"
method="POST" class="deleteForm" onsubmit='swal({
title: "Are you sure?",
text: "Your will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false,
showLoaderOnConfirm: true,
},
function (isConfirm) {
location.reload();
});'>
<button class="btn btn-xs btn-danger">Delete</button>
</form>
Coul you please assist?
Many thanks in advance,
Szymon
You have two problems.
When the submit button is clicked, you want to display the alert, but you don't want the form to submit. You've done nothing to prevent the form from submitting.
When the alert has the OK button clicked, you want to submit the form, but you are reloading the current page instead.
So, sort out the submit button first.
Don't use the onsubmit attribute. It is more trouble than it is worth.
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault(); // Stop normal form submitting
// Then include your code for showing the alert
});
Then make the alert do what you want when the OK button is selected.
function (isConfirm) {
document.querySelector("form").submit();
})
I finally found a bug in above code and now it is working perfectly in EJS file. There should be:
function archiveFunction(event) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure you want to delete the comicbook?",
text: "You will not be able to undo this action.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
form.submit(); // submitting the form when user press yes
} else {
swal("Cancelled", "Your comicbook has not been deleted.", "error");
}
});
}
Cheers,
Szymon
Anyone ever using sweet alert js? I have a question.
this is my code to delete a post by id_event:
<i class="glyphicon glyphicon-trash" onClick="return(confirm('Are you sure?'));"></i>
i want to using sweet alert js for delete confirmation. this is the code :
swal({
title: "Are you sure?",
text: "Your will not be able to recover this post!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function(){
swal("Deleted!", "Your post has been deleted.", "success");
});
i want to delete the post when i click the confirmButton.
how do i implementation the code? thanks for helping :)
You need use JS to prevent default action on this link and send AJAX request to server.
Something like this:
$('a[title=delete]').on('click', function(e) {
e.preventDefault();
$.ajax({
url: 'admin/event/delete_event/'+$(#).attr('data-id'),
method: "POST",
success: function() {
//code when success
},
error: function() {
//code when error
}
});
Unfortunately sweetAlert not have its own methods for closing modal. So I'm just returning closeModal method in the closure sweetAlert.
If you don't want to use ajax, you can't understand when delete is success or fail
First I don't have much experience with javascript and jquery :) I am just trying to find a quick way to connect jquery email validator module with a function that checks recaptcha. Here is my code:
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
Works fine! Inputs are validated.
Now after validation I need two things: First I need to call recapVerify(), after recaptcha gets validated I need to submit my form. This is the example I use: email method. I know I need to use submitHandler now but I can't figure out where and how?
Btw. this is recapVerify() function that I want to use:
function recapVerify(){
$.ajax({
type:'post',
url: 'captcha_check.php',
data: {
recaptcha_challenge_field:$('#recaptcha_challenge_field').val(),
recaptcha_response_field:$('#recaptcha_response_field').val()
}
}).done(function(data, textStatus, jqXHR){
if (data == 'success'){
$('#err').addClass('hidden');
//document.forms[0].submit(); // uncomment this line to submit your form
alert('Success, the form and reCAPTCHA validated, your form was submitted');
} else {
$('#err').removeClass('hidden');
}
}).fail(function(jqXHR,textStatus,errorThrown){
console.log('recaptcha or service failure');
});
}
use submitHandler on your jquery validate function. Debug is not needed. In essence this is the javascript you need.
$(document).ready(function(){
$("#test-form").validate({
rules: {
name: {
required: true,
},
email : {
required : true,
email : true
}
},
submitHandler : recaptchaVerify
});
});
function recaptchaVerify(form){
console.log(form);
alert("in submit handler");
}
According to the documents at jQuery validate
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it is validated.
Have also created a fiddle so that you can use it.
Good day, I have a simple html page containing this form:
<form:form method="post" action="details" modelAttribute="code">
<form:input path="code"/>
<br/>
<input type="submit" value="Submit" />
</form:form>
When I press the Submit button I need to check whether there are some records in the database for given code using jQuery AJAX. If yes then popup jQuery UI dialog to ask user whether he really wants to display record details (because it's a paid service). If he confirms I need to submit the form. This is my script on the html page:
$(document).ready(function() {
// Bind an event handler to the submit event
$('form#code').submit( function() {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
success: function(result) {
if(result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function() {
// User confirmed, submit the form
$('form#code').submit();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
When I press "Display details" button nothing happens. I think it is because I'm entering the same submit handler which returns false. How to solve it so that form submit is executed? Please advise.
Thank you in advance.
Vojtech
Change
$('form#code').submit();
to
$('form#code')[0].submit();
It will skip the jQuery onsubmit function.
Basic example: http://jsfiddle.net/4Ax6m/
There is one simple answer: Do not use <input type="submit" ... />.
You can instead use <button onlick="handler()">Submit</button>, where handler() is your function bound to the submit-event of the form in the above code. If your handler decides that the form should be submitted just submit it programmatically. Edit: Which is actually already in your code.
You'd need to wait for the .ajax to succeed since it is currently running in async mode.
So disable it using the async option on ajax. Documentation Here
ANSWER SPECIFICALLY FOR YOU
JS
$(document).ready(function () {
// Bind an event handler to the submit event
$('form#code').submit(function () {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
async: false,
success: function (result) {
if (result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
//No Records found, submitting!!
return true;
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function () {
// User confirmed, submit the form
return true;
},
Cancel: function () {
//TODO: Don't think you need this line?
$(this).dialog("close");
//CANCEL!!!
return false;
}
}
});
//User skipped Dialog somehow...ignoring....DO NOT SUBMIT
return false;
}
}
});
});
});
Note: This will return true and false to continue the submit process to the server