Submitting one form and Ajaxing too - javascript

I use below code to submit the form AND get registered in aweber email list (addlead.pl is just a registration script).
Here is what i want to accomplish:
User submits a form - it registers him in aweber email list (using two of many form fields) as it woud be signup form, then user gets redirected to normal form action url with posted information from the form (all fields)
$('#redeemform').submit(function() {
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
});
alert("thank you"); //<<magic line
return true;
});
Code works but only with magic line - alert "thank you" - without this line it woud only submit to default form action not registering to aweber.
I've figured out that if i try submitting form (return true) and in the same time send those POST requests like this - site will refresh too fast and ingnore one of the requests.
Question is how do i do it without alert / some fixed delay in this line. Is there some kind of fancy command for it ?

Absolutely BEST solution is to let your form request call weber using CURL or similar on the server
since you cannot Ajax to another domain, you need to be more inventive if you are to run this on the client
So in the submission event we
Change the target to hiddenframe2
submit the aweber form to hiddenframe1
let the main form submit to hiddenframe2
Now you need in the RESULT of your main form return something like
<script>top.location.replace("thankyou.html");</script>
assuming your form sends the request to the same server the html comes from
and have
$('#redeemform').on("submit",function() {
$(this).prop("target","hiddenframe2");
if (!$("#hiddenframe1")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe1"})
.css("display","none")
.appendTo("body");
}
if (!$("#hiddenframe2")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe2"})
.css("display","none")
.appendTo("body");
}
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$("<form>",{"action":"http://www.aweber.com/scripts/addlead.pl",
"target":"hiddenFrame1"})
.append("<input/>",{meta_web_form_id: '1234'})
.append("<input/>",{meta_split_id: ''})
.append("<input/>",{listname: 'listname'})
.append("<input/>",{redirect: ''})
.append("<input/>",{meta_adtracking: 'newsletter'})
.append("<input/>",{meta_message: '1'})
.append("<input/>",{meta_required: 'name,email'})
.append("<input/>",{meta_tooltip: ''})
.append("<input/>",{email: emailVal})
.append("<input/>",{name: nameVal})
.submit();
});
Here is what COULD have done had you been able to Ajax to aweber, which you cannot because of cross domain scripting. If they support JSONP/CORS you may be able to do it anyway
$('#redeemformButton').on("click",function() {
var $form = $('#redeemform');
var nameVal = $form.find('input[name="custname"]').val();
var emailVal = $form.find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
},function() {
$form.submit();
});
});
and have a
<input type="button" id="redeemformButton" value="Sign up and submit" />

Related

reCaptcha V3 fails validation on first form submission only

I am trying to set up reCaptcha v3 and it sort of works. For some reason the first time I submit the form it fails but from the second submit onwards it is fine. I can't figure out why this is happening?
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('MY_SITE_KEY', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
<input type="hidden" name="captcha-response" id="captcha-response">
PHP
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['captcha-response']);
$responseData = json_decode($verifyResponse);
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
When I submit the form the first time, I get the validation error but my score is 0.9.
Why you have added "!" with "$responseData->score"? you may need to replace your condition with the following:
Replace this:
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
With this one:
if($responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
P.S: Following code takes few seconds to properly load and get a "captcha-reponse" code, so you may need to disable all submit button and wait till you got a "captcha-reponse" to enable the submit button in form or you needs to implementent another way to delay the submit to execute only once you got a "captcha-response" code otherwise you will keep getting "missing-input-response" error message
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('MY_SITE_KEY', {
action: 'contact'
}).then(function(token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
You should re-generate the reCaptcha token after error form validation occured.
The token reCaptcha only valid for ONE TIME.
So, you have two options to fixes this issue.
1. Reload the page when error occured
This is the easiest way. You only need to reload the page whenever form validation error occured.
Of course, this will trigger the reCaptcha to generate new token.
2. Handle with AJAX (Non-reload page)
This is the best approach, since this will helps the user not losing the form data and continue to fill the form.
So, here's what you should do.
<!-- Put this hidden input inside of your form tag -->
<input name="_recaptcha" type="hidden">
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITEKEY_HERE"></script>
<script>
// This will generate reCaptcha token and set to input hidden
const generateRecaptcha = function() {
grecaptcha.execute(
"YOUR_SITEKEY_HERE", {
action: "YOUR_ACTION_NAME"
}).then(function(token) {
if (token) {
document.querySelector("input[name='_recaptcha']").value = token;
}
});
}
// Call it when page successfully loaded
grecaptcha.ready(function() {
generateRecaptcha();
});
// Do your AJAX code here
$.ajax({
url: "https://example.com",
success: function(response) {
console.log(response);
},
error: function(error) {
// Call again the generator token reCaptcha whenever error occured
generateRecaptcha();
}
</script>
Don't forget to put your Site key and your action name. Make sure the action name matches with your Backend action name.
Medium Article

Why does the redirected page load on top of the current page in the same browser window?

I have figured out a workaround to this problem using Javascript, but would like to know why this is happening, and to figure out a possible solution using PHP.
On my registration page (register.php) I use jQuery's preventDefault() on the submit button, but if I call header("Location: /index.php"); upon successful registration, my index page is loaded on top of my register page. The URL in my browser still says register.php as well.
Redirecting with Javascript solves the problem, but why is this happening with PHP? All other functionality of my registration script works perfectly, including other places where, upon error, I use header() to redirect users to my home page (i.e. when users try to navigate directly to .../_registerAccount.php);
jQuery:
/// <reference path="jquery-3.3.1.min.js" />
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var username = $("#register-username").val();
var email = $("#register-email").val();
var password = $("#register-password").val();
var confirmPassword = $("#register-confirm-password").val();
var submit = $("#register-submit").val();
$(".form-message").load("../shared/_registerAccount.php", {
username: username,
email: email,
password: password,
confirmPassword: confirmPassword,
submit: submit
});
});
});
PHP:
else
{
$errorEmpty = $errorUsername = $errorEmail = $errorPassword = $errorConfirmPassword = false;
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($statement, "sss", $username, $email, $hashedPassword);
mysqli_stmt_execute($statement);
session_start();
$_SESSION['register-success'] = 'You have successfully registered! Please verify your email before logging in.';
$registrationSuccessful = true;
//My Javascript workaround
//exit('<script type="text/javascript">location.assign("../index.php")</script>Home');
header('Location: ../index.php');
exit();
}

Trying to pass <%> HTML Variable to Javascript - Node, Passport, and Stripe

A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.

Sending form with PHP through AJAX with no page refresh

So I have this code to POST data with PHP and AJAX without redirecting page, I'm using the same script on the login page. The login page works like a charm but the other pages don't. The only diffeence between these is that login php script page uses if (empty($_POST) === false) {} and the other pages use if (isset($_POST['save-settings'])) {}. I don't know what do to.. Here below is the script I'm using.
HTML BUTTON
<input id="save-settings" class="submit" type="submit" name="save-settings" value="Save" onclick="return false;" />
JS SCRIPT
$(document).ready(function() {
$("#save-settings").click(function() {
var name = $("#webname").val();
var charset = $("#webchar").val();
var meta = $("#webmeta").val();
var description = $("#webdesc").val();
var startsite = $("#webstartsite").val();
var starturl = $("#webstartsiteurl").val();
var footer = $("#webfooter").val();
$.post("../lib/action.php", {
name: name,
charset: charset,
meta: meta,
description: description,
startsite: startsite,
starturl: starturl,
footer: footer
}, function(data) {
$("#gy-main-notification-bar").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#gy-main-notification-bar").slideUp(500) }, 2500);
});
});
});
PHP SCRIPT
if(isset($_POST['save-settings'])) {
$updatesettings = "UPDATE `settings` SET
`name`='".escape($_POST['webname'])."',
`charset`='".escape($_POST['webchar'])."',
`meta`='".escape($_POST['webmeta'])."',
`description`='".escape($_POST['webdesc'])."',
`startsite`='".escape($_POST['webstartsite'])."',
`starturl`='".escape($_POST['webstartsiteurl'])."',
`footer`='".escape($_POST['webfooter'])."'
WHERE `id`= 1";
if ($update_settings = $db_connect->query($updatesettings)) {}
echo 'Success!';
}
I don't really want to change the isset to empty in the script due the fact that I have all my "onclick" script in one action.php file. When I remove onclick="return:false;" from input it works.. I'm so confused I appriciate any help!
Click event handler function can have event argument. When you catch this argument you can use preventDefault() method. With this method default action of click will be prevented and page won't be refreshed.
Change
$("#save-settings").click(function() {
var name = $("#webname").val();
to
$("#save-settings").click(function(ev) {
ev.preventDefault();
var name = $("#webname").val();
You Forgot to include the post save-settings. You probably should've included it with the ajax post like this:
$.post("../lib/action.php", {
'name': name,
'charset': charset,
'meta': meta,
'save-settings': true,
'description': description,
'startsite': startsite,
'starturl': starturl,
'footer': footer
},
change this in your sql statement for the correct posts
`name`='".escape($_POST['name'])."',
`charset`='".escape($_POST['charset'])."',
`meta`='".escape($_POST['meta'])."',
`description`='".escape($_POST['description'])."',
`startsite`='".escape($_POST['startsite'])."',
`starturl`='".escape($_POST['starturl'])."',
`footer`='".escape($_POST['footer'])."'
WHERE `id`= 1";
writing onclick="return false" in HTML cancels the execution of the javascript code. just delete this onclick="..." and add preventDefault() like this to prevent form submittion
$("#save-settings").click(function(e) {
e.preventDefault();
.....

window.location.replace not working

i have written a javascript function thats posts a form and redirect to home page . Im using window.location.replace to get to home page. but instead of replacing the url the function is appending the url in front of current url. Whats the problem?
$('#submit_fourth').click(function () {
// send data to server to save in table dbo.aspnet_Users =================================================
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
$.post("/Account/Register", { FirstName: firstname, LastName: lastname, UserName: username, Password: password, ConfirmPassword: password, Email: email });
//send information to server
alert('Congratulations! Your account has been sucessfully created.');
//get back to the login screen
window.location.replace("dgsmart/Central/Login");
current url is 184.180.25.240/dgsmart/account/register after register button click it becomes 184.180.25.240/dgsmart/account/central/login
i want url lyk this 184.180.25.240/dgsmart/central/login
I assume you are using a form onsubmit event to call some function, if so you have to prevent the default behavior by return false; (for example)
window.location.replace("absolute-address"); /*window.location.replace('http://example.com/#' + initialPage); */
return false; //prevent the default behavior of the submit event
You can also using this code to set your ideal url...
<script>
location.href='RegisterNew.php';
</script>

Categories

Resources