woocommerce POSTing data before javascript (jQuery) finishes - javascript

i have a custom gateway (which works perfectly), the problem is when a customer buys something for the first time, there is some token than needs to be generated with the card info, the thing is that just before that token is generated, the form tries to submit, but an error is displayed saying that "the object could not be found", so, no refresh and nothing, if i press again the submit button (or "place order" button) everything works!.
i believe that by that second time, the token is generated and in the corresponding hidden field:
here is my code, hope somebody could help me :S
HTML (from the chrome inspector):
<input type="hidden" name="card-name" data-conekta="card[name]">
<input type="hidden" name="exp-month" data-conekta="card[exp_month]">
<input type="hidden" name="exp-year" data-conekta="card[exp_year]">
<input type="hidden" name="conektaTokenId" value="">
<input type="hidden" name="conektaCustId" value="false">
Javascript
jQuery(window).load(function() {
var form;
var first_name;
var last_name;
var cvc;
jQuery('form[name="checkout"]').submit(function(event) {
jQueryform = jQuery(this);
Conekta.setPublishableKey(jQuery('input[name="pbkey"]').val());
console.log('entro');
if( jQuery('input[name="conektaCustId"]').val()=="true" && jQuery('input[name="conektaTokenId"]').val().substr(0,4)!="tok_"){
console.log('entro');
first_name = jQuery('#billing_first_name').val();
last_name = ' ' + jQuery('#billing_last_name').val();
expiry = jQuery('#conekta_card-card-expiry').val().replace(/ /g, '').split("/");
jQuery('input[name="card-name"]').val( first_name + last_name );
jQuery('input[name="exp-month"]').val( Number(expiry[0]));
jQuery('input[name="exp-year"]').val( Number(expiry[1]));
jQueryform.prepend('<span class="card-errors"></span>');
Conekta.token.create(jQueryform, conektaSuccessResponseHandler, conektaErrorResponseHandler);
woocommerce_order_button_html
return false;
}
else{
return;
}
});
var conektaSuccessResponseHandler= function(response){
var token_id = response.id;
jQuery('input[name="conektaTokenId"]').val(token_id);
}
var conektaErrorResponseHandler= function(response){
jQueryform.find('.card-errors').text(response.message);
}
});

i have found the solution, you have to add the class processing to the checkout form and just when you finished procesing your data to be send to wherever you need to (usually wordpress/woocommerce), remove that class so the form can submit the new data.

Related

form input reload page with appended url

I have the following form posted on a wordpress page.
I´d like to catch users without referrers to set the referrer on their own (that referrer part is all handled by a plugin... does not matter here).
The registration form Url is like:
http://myurl.com/register/
The code below just works fine. Inserted directly into the wp page editor (text).
Except it creates a Url like follows:
http://myurl.com/register/?id=testinput
How do i get the resulting Url to be formatted this way?:
http://myurl.com/register/sp/testinput
<h3>Your ID</h3>
<p>Please input your ID</p>
<form id = "submit_id_form" onsubmit="myIDFunction()">
<input type="text" name="id">
<input type="submit" value="Confirm">
</form>
<?php
function myIDFunction(){
var action_src = "http://myurl.com/register/" + document.getElementsByName("id")[0].value;
var submit_id_form = document.getElementById('submit_id_form');
submit_id_form.action = action_src ;
} ?>
</script>
This is the original form code (reference below) i`m trying to modify:
<form id = "your_form" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="submit" value="Search">
function yourFunction(){
var action_src = "http://localhost/test/" +
document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>
I tried to append the /sp/ part and remove the appended question mark "?" in the code above.. but i´m totally stuck with coding. (I´m a "clicker" not a coder so to speak)
Thank you very much guys and gals :)
Original Code is from here
You have to return true from method called on onsubmit as
function yourFunction(){
var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
return true;
}

Google apps Script won't record submissions

Below is a program that I put together, from research and some of my own adding, and I'm having many issues with it. The record_submission function isn't working properly. Every time I test with someone submitting their name, it won't properly record the information which then effects the next function, the notification function which I wrote to automatically send me an email once someone submits a response. Would appreciate some help.
Attached are the images of the Google spreadsheet that I want updated whenever someone submits a response as well as the face of the website people will be submitting information from. The record function is supposed to do that. It's giving me a error saying that the variable isn't properly assigned or something of the sort and the notification email doesn't work properly either.
This is the whole JavaScript code:
//* This function handles the get request from the web browsers */
function doGet(e)
{
//return form.html as the response return
HtmlService.createHtmlOutputFromFile('form.html');
}
// Record all the information entered into the form into a Google Sheet.
function record_submission(form)
{
Logger.log(form);
var ss = SpreadsheetApp.openById("1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8");
var sheet = ss.getSheets()[0]; // Assume first sheet collects responses
// Build a row of data with timestamp + posted response
var row = [ new Date(), // Timestamp
form.last_name[0], // last name
]; // Make sure we are the only people adding rows to the spreadsheet
var lock = LockService.getPublicLock(); // Wait for up to 30 seconds for other processes to finish.
var locked = lock.tryLock(30000);
if (locked)
{
// Save response to spreadsheet
var rowNum = sheet.getLastRow() + 1;
sheet.getRange(rowNum, 1, 1, row.length).setValues([row]);
// Release the lock so that other processes can continue.
lock.releaseLock();
var result = "Response Recorded: \n
"+row.join('\n ');
}
else
{
// Failed to get lock
result =
"System busy, please try again.";
}
// Report result of POST, in plain text
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}
// Send an email to yourself notifying you when someone made a submission.
function notification(last_name, assignment_name)
{
var subject = "New Submission"; MailApp.sendEmail("*my email*#gmail.com",
subject, 'New submission received from ' + last_name + ' for the
assignment: ' + assignment_name );
}
/* This function will process the form when the submit button is
clicked */
function uploadFiles(form)
{
try
{
notification('test','test'); //Retrieve a reference to the folder in Google Drive
var folder_name = "Test_Folder"
var folder =
DriveApp.getFolderById("0By69oDzO6OluTm9KNGVuaUZZdE0");
// Create a new folder if the folder does not exist
if (!folder)
{
folder = folder.createFolder(folder_name);
}
//Get the file uploaded through the form as a blob
var blob = form.myFile;
var file = folder.createFile(blob);
//Set the file description as the name of the uploader
file.setDescription("Uploaded by " + form.LastName);
//Set the file name as the name of the uploader
file.setName(form.LastName + "_" + form.AssignmentName);
//This function should store the information of the submission to a Google Sheet
record_submission(form);
//This function should notify you when there has been a submission
notification(form.LastName, form.AssignmentName);
// Return the download URL of the file once its on Google Drive
return "File uploaded successfully " + file.getUr1();
}
catch(error)
{
// If there's an error, show the error mesage return
error.toString();
}
}
This is the whole HTML code
File Upload
<!--User inputs -->
<h4>First name</h4>
<input type="text" name="FirstName" placeholder = "Type your first name.." >
<h4> Last Name </h4>
<input type="text" name = "LastName" placeholder="Your last name...">
<h4> Assignment Name </h4>
<input type="text" name="Course" placeholder="Course number">
<!--File upload-->
<h4>Upload</h4>
<input type="file" id="file" name="myFile" style="display:block; margin: 20px;" value = "myFile">
<!-- Submit button -->
<input type="submit" value="Submit"
onclick= "this.value='Uploading..';
google.script.run.withsuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form> <div id="output"> </div> <script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
/*check to see if the user's first name input is empty.
If it is empty alert the user to fill in his/her first name */
</script>
<style>
input {display:block; margin: 20px; }
</style>
</body> </html>
I see that your 'input' tags are not wrapped in a 'form' tag, so what gets passed to the 'onclick' function as parameter might actually be the entire <body> tag. Are your inputs nested inside the <form> tag? If not, then this.parentNode would be the entire body of the HTML document.
I put together the quick example illustrating the entire process. On the client side, we are listening for the form submit event. Once the event fires, we call the server-side function via google.script.run and pass the form object to that function as an argument.
Code.gs
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('siderbar'));
}
function logFormObject(form){
Logger.log(form); //check the logs by pressing Ctrl + Return
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // get the 1st sheet in the spreadsheet
sheet.appendRow([form.name, form.lastName, form.age]); //create row contents array from the form object and pass it to the appendRow() method
}
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
Name <br>
<input name="name" /> <br>
Last Name: <br>
<input name="lastName" /> <br>
Age: <br>
<input name="age" /> <br>
<input type="submit" value="send">
</form>
<script>
window.onload = function(){
var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); //prevents redirect to another page
google.script.run.logFormObject(this); // calling the server function in Code.gs
});
}
</script>
</body>
</html>

Why won't this script load?

I have a contact us form:
<form id="contactus" name="contactus" action="html_form_send1.php" method="post">
<label for="name">Name:</label><br />
<input type="text" id="name" name="name" maxlength="50" size="59" autofocus required/><br /><br />
<label for="email">E-Mail Address:</label><br />
<input type="email" id="email" name="email" maxlength="50" size="59" required/><br /><br />
<label for="question">Question:</label><br />
<textarea id="question" name="question" maxlength="1000" cols="50" rows="6" required></textarea><br /><br />
<input class="c1_scButton" type="submit" id="submit" name="submit" value="Send" />
</form>
I want it to call my mail PHP script using this AJAX code:
var msg = "";
name = $("#name").val();
email = $("#email").val();
question = $("#question").val();
//validation phase
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
function validate(e) {
if (name == "") {
msg = " valid name";
}
if (!isValidEmailAddress(email)) {
msg = msg + " valid email address";
}
if (question == "") {
msg = msg + " valid question or comment";
}
}
// on submit, Validate then post to PHP mailer script
$(function() {
$("#contactus").on('submit', function(e) {
e.preventDefault();
validate(e);
if msg != "" {
e.preventDefault();
$("#alert").html "Please enter a" + msg;
} else {
$.post('/html_form_send1.php', $(this).serialize(), function(data) {
$('#alert').css(color: "black")
$('#alert').html("<h2>Thank you for contacting us!</h2>")
.append("<p>We will be in touch soon.</p>");
}).error(function() {
$('#alert').css(color: "red")
$('#alert').html("<h2>Something went wrong. Your Question was not submitted. /n</h2>").append("<p>Please try again later or email us at <a href=href="
mailto: support# allegroaffiliates.com ? Subject = Contact Us Form " target="
_top ">support#allegroaffiliates.com.</a> </p>");
});
};
});
});
The script is called at the bottom of the HTML page after another script, but it isn't loading. I suspect that it is due to a code error but I can't find the error. Can anybody give me an idea why it wont load?
Side note: I do know that HTML5 will validate the script, but I have the validation in place for when HTML5 is not available.
Thank you for your help.
A few troubleshooting suggestions:
(1) When specifying the ajax processor file, either this $.post('html_form_send1.php' or this $.post('./html_form_send1.php' but not this $.post('/html_form_send1.php'
(2) Instead of using the shortcut code $.post(), use the full form of the method until you are pretty good at it:
var varvalue = $('#first_name').val();
var nutherval = $('#last_name').val();
$.ajax({
type: 'post',
url: 'your_secondary_file.php',
data: 'varname=' +varvalue+ '&lname=' +nutherval,
success: function(d){
if (d.length) alert(d);
}
});
(3) Disable validation routine until the rest is working, then work on that when you know everything else is working correctly
(4) Change your ajax processor file html_form_send1.php to just echo back a response to make sure you've got the AJAX working. Then, once you get the response, change it to echo back the variable you are sending. Then build it into the final desired product. But initially, something dead simple, like this:
your_secondary_file.php:
<?php
$first_name = $_POST['varname'];
$last_name = $_POST['lname'];
echo 'Received: ' .$first_name .' '. $last_name;
die();
(5) Instead of using .serialize(), initially just grab one or two field values manually and get that working first. Note that .serialize() produces JSON data, while the simpler method is straight posted values, as in sample code in this answer. Get it working first, then optimize.
(6) Note that the dataType: parameter in the AJAX code block is for code coming back from the PHP side, not for code going to the PHP side. Also note that the default value is html, so if you aren't sending back a JSON object then just leave that param out.
(7) In my AJAX and PHP code samples above, note the correlation between the javascript variable name, how it is referenced in the AJAX code block, and how it is received on the PHP side. I was very deliberate in the names I chose to allow you to follow the var name => var value pairing all the way through.
For example, the input field with ID first_name is stored in a variable called varvalue (dumb name but intentional). That data is transmitted in the AJAX code block as a variable named varname, and received on the PHP side as $_POST['varname'], and finally stored in PHP as $first_name
Review some simple AJAX examples - copy them to your system and play with them a bit.

How to dynamically show error messages through PHP

I am creating a PHP login script. So far I have only worked on the registration.
My question is, how can I handle validation in PHP without refreshing the page? I want to output the feedback that the user has entered information wrongly, but I don't want to refresh the page. This is because I am using AJAX, so I want it to output on the page.
Is this possible?
See here, if you "sign up" without filling in any of the boxes it shows you some error messages. The problem is that it reloads the page as it does it. Is there a way to not reload the page and still show this data?
http://marmiteontoast.co.uk/fyp/login-register/test/index.php
This is an example of the if statement for just the username. This is repeated with all the other fields too:
if(isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
if(strlen($username) > 3){
// passed
if(strlen($username) < 31){
// passed
} else {
$_SESSION['status']['register']['error'][] = 'The Username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 4 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The Username is not entered.';
}
Once it passes all the validation it does:
header('Location:index.php');
And the errors are output on the index page by:
<?php
if(isset($_SESSION['status']['register']['error'])){
?>
<div class="alert alert-error">
<p><strong>There's a problem!</strong><br /><br />
<?php
foreach($_SESSION['status']['register']['error'] as $error){
// Outputs list of all errors, breaks to new line
echo $error . '<br />';
}
?>
</p>
1. Is it possible to output these dynamically with PHP?
2. Could I do the validation on the front end, then just pass it to the PHP to pass to the database?
2a. How would I handle running a username exists check if I do it front end?
This is something I actually just made the other day!
I have a file called "register.js", a file called "register_process.php" and some html.
How my server is set up:
html_docs (www):
ajax:
register_process.php
js:
register.js
jquery-1.6.2.js
register.html
so within my register.html, my code looks like such:
<script type="text/javascript" src="js/md5.js"></script> <!-- this is in my head -->
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<!-- everything else is in my body -->
<div id="error_message" style="display: none;">
</div>
<div id="register_div">
<input type="text" name="username" id="username"><br>
<input type="password" name="password" id="password"><br>
<input type="submit" name="submitbutton" id="reg_button" value="Register" onclick="AttemptRegisterAjax(); return false;"><br>
</div>
This calls the function inside of my register.js file. That functions looks like such:
function AttemptAjaxRegister(){
var url = "ajax/register_process.php?";
url += "time=" + (new Date().getTime()) + "&un=";
var username_ele = document.getElementById("reg_username");
var password_ele = document.getElementById("reg_password");
var error_ele = document.getElementById("error_message");
var username = username_ele.value;
var password = password_ele.value;
if((username.length >=4) && (password.length >= 4)){
url += encodeURIComponent(username) + "&pw=" + encodeURIComponent(password);
console.log(url);
$.get(url, function(data, status, xhr){
data = data.trim();
if(data != "true"){
error_ele.innerText = data;
error_ele.style = "display: block;";
}else{
window.location = "/profile.php";
}
});
}else{
error_ele.innerText = "Please make sure your password and username are both 4 characters long";
error_ele.style = "display: block;";
}
}
now, inside of your php, you'll want to set everything up just like how you had it to register, but you'll want to actually just call die($YourErrorMessage); or if the registration was successful, die("true");
Not directly, you will need to use another tool for that, most likely Javascript.
Yes but that would be a terible practice. the best way to validate on both.
2a. I believe you would need to use a database.
thsi tutorials might help you out.
Easy jQuery Ajax PHP Contact Form
How to create a Sign Up form registration with PHP and MySQL

passing old value back to javabean from javascript

I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{
var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;
if (type == "Update")
{
if(old_cd != new_cd)
{
var response = confirm("Code already exists. Do you want to replace it?");
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
}
}
</script>
and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">
Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database
I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
return false;
}
If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">
and javascript:
// js snippet
if (response){
document.NameUpdate.submit();
}
else{
document.getElementById("canceled").value = 1;
return true;
}

Categories

Resources