How do I submit this form without page reload? - javascript

So basically I have this interest slider plugin that calculates the repayments on a loan over a certain period of time - https://loancalc.000webhostapp.com/
But the problem I am having is submitting the form without reloading the page, currently you enter your name and email.
I have included this ajax script on line 1146 of slider.js but the slider continues to reload the page when submitting the form.
I am told it could be because i'm not enqueuing the script (for wordpress) properly.
jQuery('.qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}});
The full code is here (slider.js, quick-interest-slider.php, register.php) - https://github.com/Curnow93/quick-interest-slider/tree/master/quick-interest-slider

There's no submit event on the input. It should be on the form. Also, you need to pass the event to the callback function.
jQuery('.qis_form').on('submit', function(event) {
Also your selector doesn't select anything. I have updated it using the right selector.

Related

Google reCAPTCHA reset multiple captchas rendered by function call

I have many reCAPTCHA's who are rendered dynamically, sometimes there are 2 sometimes 50 depends on page.
I've done rendering with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {'sitekey' : 'myKey'});
});
};
And placed this where I want captcha to be displayed:
<div class="g-recaptcha" data-sitekey="myKey"></div>
I've got ajax call, that submits form data to process.php, and if form data isn't verified returns custom errors
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
dataType : 'json'
})
.done(function(data) {
if ( ! data.success) { ...
It works as intended, but now I want to show message to user as part of validation, if he forgot to solve captcha.
With
var response = grecaptcha.getResponse();
if(response.length == 0){
$('.result').append('Captcha incorrect, please click I am not robot');
}
and to reset captcha add this bellow
if ( ! data.success) {
grecaptcha.reset();
What does it do is: reset captcha if user didn't completed all forms valid.
This all works only on 1st occurrence of reCAPTCHA.
And I need it to somehow tell it to reset only captcha that is currently in use.
My best guess was to try with
var form = $(this); //get current form
grecaptcha.reset(form);
It won't work, since i need widget ID, and not form.
Can you assist me pls?
All credits to https://stackoverflow.com/a/41860070/7327467
reset is done with
var form = $(this); //store current form
var response = grecaptcha.getResponse(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
if(response.length == 0){ //append error to result div
form.find('.result').append('<div class="alert alert-danger">' + "Captcha incorrect" + '</div>'); }
and to reset recaptcha, I've added this instead previous "grecaptcha.reset();"
grecaptcha.reset(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
Hope this helps.

preventDefault before AJAX, form still submits with success

I'm trying to make a form that requires certain things to be true before submitting. Running into some issues with ajax here..
$('form').submit(function(event){
form = $(this); // I've tried just: this. Same result
material = $('#material'). val();
hours = $('#hours'). val();
// - Material and Hours are numbers
if(isNaN(material)) {
event.preventDefault();
alert('Please enter a number for Material');
}
if(isNaN(hours)) {
event.preventDefault();
alert('Please enter a number for Hours');
}
event.preventDefault();
$.ajax({
url : 'page.php',
data : {
'id' : {{ id }}
},
type : 'post',
dataType: "json",
success : function(data){
console.log(data);
if(data.job_num == {{ job_id }}) {
form.submit();
} else {
alert('Please enter a valid number');
}
},
error: function(){
alert('Please enter a valid number');
}
});
});
As you can see, hours could be NaN and the form will not submit.. but when it gets to the ajax and if it is successful, the form will submit even if hours is still NaN..
I've tried putting the ajax before the if statements, same result.. Not sure if this is something simple that I'm overlooking, or if it's really this complicated..
Put a return; after you error alert() and it will end the event function no metter what.
event.preventDefault() will prevent the form to be submitted, and not the rest of function to be executed, that is why your ajax request keeps being executed.

Use jScript / AJAX to call PHP script but ONLY if form has been submitted?

This is kind of a follow up to this question.
I have this code:
var chpass = function()
{
var pass1 = encodeURIComponent($("#pass1").val());
var pass2 = encodeURIComponent($("#pass2").val());
$.ajax(
{
type: "POST",
url: "lib_ajax/somescript.php",
data: "pass1="+ pass1+"&pass2="+ pass2,
success: function(msg_pass)
{
$("#status_pass").ajaxComplete(function(event, request, settings)
{
if(msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
});
}
});
}
$("#signup").ready(chpass);
$("#signup").change(chpass);
And in the php script:
$pass1 = trim($_POST['pass1']);
if(!isset($pass1)||empty($pass1)) die('empty pass1');
My problem is that I don't want the form to be validated with ready() the first time the page is loaded but every time the page is loaded after a submit.
I have tried to figure out how to set a default event for the handler and then use preventDefault but I've been completely unsuccessful so far.
Could part of the problem be that when the page is submitted some additional validation happens on the server and in some cases I use header('Location: ') to reload the page?
Any tips how I can work this out? Is there a way to change it to something like:
if ( FORM IS SUBMITED ) $("#signup").ready(chpass);
Or maybe:
if ( FORM IS SUBMITED && msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
Can also add that I have tried to change ready() to submit() with no luck:
$("#signup").submit(chpass); // DO NOT WORK
I finally found a solution. Change the code:
$("#signup").ready(chpass);
to:
<?php if(isset($_POST['submit'])) { ?>$("#signup").ready(chpass);<?php } ?>
and that part of the jScript is left out unless the form is submitted!

Display the following AJAX in a blank/new page

I want to display the part which comes with the AJAX code in a new or blank page, without getting the requested url under the "old" html code on the same page.
d$(document).ready(function() {
$("#bestello").submit(function() {
if($("#nn").val() == "" || $("#vn").val() == "" || $("#strt").val() == ""){
$("#response").html("Bitte füllen Sie alle Felder aus!");
} else {
$.ajax({
type: "POST",
url: "test.php",
data: "nn=" + $("#nn").val() + "&vn=" + $("#vn").val() + "&strt=" + $("#strt").val(),
success: function(msg)
{
$("#response").html(msg);
}
});
}
return false;
});
});
Everything after the else or $.ajax({ should be displayed in a blank/new page.
How can I solve this problem?
You are looking for popup functions.
Place the following code inside your success function
var w = window.open('', '', 'width=400,height=400,resizeable,scrollbars');
w.document.write(msg);
w.document.close(); // needed for chrome and safari
Rather than submitting the form with ajax, allow the form to be submitted using its native functionality. Add the attributes target='_blank' action='test.php' method='post' to the form so that it will submit to test.php using post and open in a new tab/window.
You can still use javascript to validate the form. Your code would look like this:
$(document).ready(function() {
$("#bestello").submit(function() {
if($("#nn").val() == "" || $("#vn").val() == "" || $("#strt").val() == ""){
$("#response").html("Bitte füllen Sie alle Felder aus!");
return false;
}
return true;
});
});
This will validate the form with javascript and only allow it to submit if it passes validation. (As a side note, you should make sure that you do some server side validation as well).

Save 2 Forms At the Same Time MVC 3

Im planning to save 2 forms but the 1st form is where i get the Foreign key for the Second form
This is my Attempt to save this Using Javascript
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#conttForm').submit();
});
But it errors on Contact Form Submit because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
i also Tried this method
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only go at Else because the ID is 0
I hope someone can help me here
Thanks :D
jQuery's submit function actually causes the browser to send a request, i.e. you're submitting the form. To accomplish this you'll need to uses ajax. Something like this should do the trick:
$.ajax({
method: 'POST',
url: $('#workForm').attr('action'),
data: $('#workForm').serialize(),
success: function(data) {
//grab whatever id you need here
var id_thing = $(data).find('#id_here').val();
//do something with id
$('#conttForm input[name="your-hidden-id-field"]').val(id_thing);
$('#conttForm').submit();
}
})

Categories

Resources