Native checkout WooCommerce - AJAX issue - javascript

I am developing a custom plugin for WooCommerce using viva payments. The documentation is here. It will be a native plugin
https://github.com/VivaPayments/API
The issue
Currently I have to dequeue the wc-checkout script to get it to work
wp_dequeue_script( 'wc-checkout' );
The reason for dequeue is that viva uses a card handler, and using onblur events makes XHR requests to viva. Looking in the network tab the XHR request called is
https://demo.vivapayments.com/api/cards/installments?key=mykey
and the response is {"MaxInstallments":0}
If i don't deqeue the script this request isn't made. If the request isn't made when I try and get the token I get served an error saying "Expiration date could not be parsed"
Here is the jscode
function getToken(){
VivaPayments.cards.requestToken( function(){
});
}
function tokenMyFunction() {
VivaPayments.cards.requestToken( function(){
//do something?
});
}
$(document).ready(function (){
if (viva_params.testMode === '1'){
var url = "https://demo.vivapayments.com"
} else {
url = "https://www.vivapayments.com"
}
VivaPayments.cards.setup({
publicKey: viva_params.publishableKey,
baseURL: url,
cardTokenHandler: function (response) {
//console.log(response)
if (!response.Error) {
//console.log(response.Token)
$('#hidToken').val(response.Token);
return false;
}
else{
console.log(response);
alert(response.Error);
return false;
}
},
installmentsHandler: function (response) {
if (!response.Error) {
if (response.MaxInstallments == 0)
return;
$('#drpInstallments').show();
for(i=1; i<=response.MaxInstallments; i++){
$('#drpInstallments').append($("<option>").val(i).text(i));
}
}
else
alert(response.Error);
}
});
});
Here is the viva js from their server that is used
https://demo.vivapayments.com/web/checkout/js
Here is the form
<form action="index.php" method="POST" id="payment-form">
<div class="form-row">
<label>
<span>Cardholder Name</span>
<input class="form-field" type="text" size="20" name=”txtCardHolder” autocomplete="off" data-vp="cardholder"/>
</label>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input class="form-field" type="text" size="20" maxlength="16" name=”txtCardNumber” autocomplete="off" data-vp="cardnumber"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVV</span>
<input class="form-field" type="text" name=”txtCVV” size="4" autocomplete="off" data-vp="cvv"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" class="form-field" name=”txtMonth” autocomplete="off" data-vp="month"/>
</label>
<span> / </span>
<input type="text" class="form-field" class="lukeexpiry" size="4" name=”txtYear” autocomplete="off" data-vp="year"/>
</div>
<div class="form-row">
<label>
<select id="drpInstallments" value="0" name="drpInstallments" style="display:none"></select>
</label>
</div>
<div class="form-row">
<button type="button" onclick="getToken()">Get Token</button>
</div>
<input type="hidden" name="OrderId" value="146228" /> <!--Custom Field-->
<input type="hidden" name="hidToken" id="hidToken" /> <!--Hidden Field to hold the Generated Token-->
</form>
Like I said:
When I dequeue the wc-checkout, viva makes the request fine to api/cards/instalments and thus subsequently when I call tokenMyFunction() gets the token fine
If I don't dequeue I get an error about expiration on token request
How can I let viva still make requests alongside the wc-checkout script, or what in the hell is that call to instalments doing?
Why does that impact the token request. I can't see anywhere where the response {"MaxInstallments":0} is used again?
Any provided help is welcome.

Related

How to submit a form to an external page using C# ASP.NET?

I am trying to submit data from a form to an external web page, but after submitting it, a "Thank you for contacting us" page appears.
<form action="HTTPS://WWW.externalPage.com/encoding?encoding=UTF-8" method="POST" class="row">
<div class="col-6">
<label class="form-label" for="first_name">first_name: </label>
<input class="form-control mb-3" id="first_name" maxlength="40" name="first_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="last_name">last_name: </label>
<input class="form-control mb-3" id="last_name" maxlength="80" name="last_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="mobile">mobile: </label>
<input class="form-control mb-3" id="mobile" maxlength="40" name="mobile" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="email">email: </label>
<input class="form-control mb-3" id="email" maxlength="80" name="email" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="company">company: </label>
<input class="form-control mb-3" id="company" maxlength="40" name="company" required size="20" type="text" />
</div>
<div class="col-12 buttonSubmit">
<input class="btn btn-dark" type="submit" name="submit" onclick="Gracias()">
</div>
</form>
With this I am sending the data to the controller, but it must go to another web page (ex: http://web.ReciveData.com/)
I tried to send the form to the web page like this
<form action="http://web.ReciveData.com/" method="POST" class="row">
Submit button with "Thanks()" function:
<input class="btn btn-dark" type="submit" name="submit" onclick="Thanks()">
JavaScript:
function Thanks() {
window.location.href("http://web.MyWebPage.com/Home/Thanks")
}
Also try this:
document.addEventListener('DOMContentLoaded', function () {
var formulario = document.getElementById('form');
var validateName = function (e) {
if (formulario.first_name.value.length == 0) {
return false;
}
return true;
};
var validateEmail = function () {
if (formulario.email.value.length == 0) {
return false;
}
return true;
};
var validatePhone = function () {
if (formulario.mobile.value == "") {
return false;
}
return true;
};
var validateMsj = function () {
if (formulario.mensage.value.length == 0) {
return false;
}
return true;
};
var validar = function () {
return validateName() &&
validateEmail() &&
validatePhone() &&
validateMsj();
};
formulario.addEventListener("submit", handleSubmit);
async function handleSubmit(event) {
event.preventDefault();
if (validar()) {
const form = new FormData(this);
const response = await fetch(this.action, {
method: this.method,
body: form,
headers: {
'Accept': 'application/json'
}
});
if (response.ok) {
this.reset();
window.location.href = 'Http://web.MyWebPage.com/Home/Thanks'
}
}
}
});
But it does not work. Basically what I'm trying to do is load the data, send it to the external web page, and a web page that I created to thank the contact is displayed.
I can think of absolutely nothing, and what I found on the internet are mostly basic examples..
I changed the header to
headers: {
/* 'Accept': 'application /x-www-urlencoded'*/
'Access-Control-Allow-Origin:': 'https://www.externalPage.com'
}
And now the problem is on line fetch(this.action):
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name
at HTMLFormElement.handleSubmit

Display Jquery Response in HTML

I am learning PHP and JavaScript. I have form using DropZone.js which upload files and giving response using Jquery Like below
<form class="dropzone" id = "image-upload" method="POST" action="upload.php">
<div class="form-label-group">
<input type="text" id="brand" class="form-control" placeholder="Brand Name" required autofocus>
<label for="brand"></label>
</div>
<div class="form-label-group">
<input type="text" id="reference" class="form-control" placeholder="Reference" required>
<label for="reference"></label>
</div>
<div class="form-label-group">
<input name="attached_files" value="" />
</div>
</form>
and JavaScript Like below
<script type="text/javascript">
Dropzone.autoDiscover = false;
jQuery(".dropzone").dropzone({
acceptedFiles: "image/*",
maxFilesize: 2, // MB
success : function(file, response) {
//console.log(file);
console.log(response);
if (response['target_file'] != '') {
var currentValue = jQuery("#image-upload input[name='attached_files'").val();
if (currentValue == '') {
jQuery("#image-upload input[name='attached_files'").val(response['target_file']);
} else {
jQuery("#image-upload input[name='attached_files'").val(currentValue + ", " + response['target_file']);
}
}
}
});
</script>
Its working fine as expected and showing me uploaded files in
<input name="attached_files" value="" />
But instead I want it as comma separated and <pre></pre> so it can look more better. Let me know if someone can help me for achieving my goal.
Thanks!

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

AJAX does not respond to form submission

I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!
Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});
The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready

Categories

Resources