I have a payment form as follows
<body>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<div class="content">
<h1>Secure Checkout</h1>
<g:form name="paymentForm"
method="POST"
action="processAcceptPayment" >
<input type="text" name="cardNumber" id="cardNumber" placeholder="cardNumber"/> <br><br>
<input type="text" name="expMonth" id="expMonth" placeholder="expMonth"/> <br><br>
<input type="text" name="expYear" id="expYear" placeholder="expYear"/> <br><br>
<input type="text" name="cardCode" id="cardCode" placeholder="cardCode"/> <br><br>
<input type="hidden" name="dataValue" id="dataValue" />
<input type="hidden" name="dataDescriptor" id="dataDescriptor" />
<button type="button" onclick="sendPaymentDataToAnet()">Pay</button>
</g:form>
</div>
<g:javascript>
function sendPaymentDataToAnet() {
var authData = {};
authData.clientKey = "valid key";
authData.apiLoginID = "valid id";
var cardData = {};
cardData.cardNumber = document.getElementById("cardNumber").value;
cardData.month = document.getElementById("expMonth").value;
cardData.year = document.getElementById("expYear").value;
cardData.cardCode = document.getElementById("cardCode").value;
var secureData = {};
secureData.authData = authData;
secureData.cardData = cardData;
// If using banking information instead of card information,
// send the bankData object instead of the cardData object.
//
// secureData.bankData = bankData;
Accept.dispatchData(secureData, responseHandler);
}
function responseHandler(response) {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
} else {
paymentFormUpdate(response.opaqueData);
}
}
function paymentFormUpdate(opaqueData) {
document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
document.getElementById("dataValue").value = opaqueData.dataValue;
document.getElementById("cardNumber").value = "";
document.getElementById("expMonth").value = "";
document.getElementById("expYear").value = "";
document.getElementById("cardCode").value = "";
document.getElementById("accountNumber").value = "";
document.getElementById("routingNumber").value = "";
document.getElementById("nameOnAccount").value = "";
document.getElementById("accountType").value = "";
document.getElementById("paymentForm").submit();
}
</g:javascript>
</body>
This generates the form as follows
I enter test credit card numbers and click Pay.
I get the following error in my javascript console.
I was just following the accept.js tutorial from the official page.
https://developer.authorize.net/api/reference/features/acceptjs.html
I appreciate any help as to the reason for this "Encryption Failed" error? Thanks!
UPDATE:
Ok so i did some more debugging. I put a test code "console.log("test");" inside responseHandler() function and noticed that it was called twice. I am now wondering why is responseHandler() being called twice.
When Accept.js triggers the callback function twice due to some other Javascript error occurring on the page, you can pretty quickly track down the source of that error on the by wrapping the contents of your callback function in a try/catch block:
Accept.dispatchData(secureData, responseHandler);
...
function responseHandler(response) {
try {
if (response.messages.resultCode === "Error") {
var i = 0;
while (i < response.messages.message.length) {
console.log(
response.messages.message[i].code + ": " +
response.messages.message[i].text
);
i = i + 1;
}
}
} catch (error) {
console.log(error);
}
}
Ok so i did some more debugging. I put a test code "console.log("test");" inside responseHandler() function and noticed that it was called twice. I am now wondering why is responseHandler() being called twice.
I repeated this test and can confirm that this is a common cause of this error. It is also true that Accept.js will mistakingly call your responseHandler() twice if it calls a function that has a Javascript error in it, or some other Javascript error is in the page. In my case, I had a sendOrder() AJAX function that was assuming a variable. Once I fixed that other function, the responseHandler() function was called only once.
The same error appeared to me too. Instead seeing the console, I go to the Network tab of Chrome browser and then see the success message has already appeared as below:
opaqueData
:
{dataDescriptor: "COMMON.ACCEPT.INAPP.PAYMENT",…}
Please note, while testing, enter the test cards for sandbox from https://developer.authorize.net/hello_world/testing_guide/
Related
The form works fine with the parameter action= "(path to php file)", but when I try to use the XMLHttpRequest instead I don't get any response.
The reason I want to use XMLHttpRequest is that I want to save the response (text) into an array.
function receivedData(serverReply) {
if (serverReply.readyState == 4 && serverReply.status == 200) {
document.getElementById('main').innerText = serverReply.responseText;
}
else {
console.debug('problem ' + serverReply.errorCode);
}
}
function sendRequest() {
let myForm = new FormData(document.getElementById('timeDateFormId'));
let xhr = new XMLHttpRequest();
xhr.open("POST", "get3.php");
xhr.addEventListener('readystatechange', function () { receivedData(xhr) }, false);
xhr.send(myForm);
}
document.getElementById('timeDateFormId').addEventListener('submit', sendRequest, false)
<form id="timeDateFormId" method="post">
<label>From date (YYYYMMDD)</label>
<input type="text" name="fDate">
<br>
<label>To date (YYYYMMDD)</label>
<input type="text" name="tDate">
<br>
<label>From time (HH:MM)</label>
<input type="text" name="fTime">
<br>
<label>To time (HH:MM)</label>
<input type="text" name="tTime">
<br>
<input type="submit" name="submit" value="go">
</form>
You call the sendRequest method when you submit the form.
Submitting the form causes the browser to navigate to the response from the form submission.
This loads a new page which cancels the Ajax request.
You need to prevent the default behaviour of form submission if you want to run JavaScript instead.
function sendRequest(evt) {
evt.preventDefault();
// etc
I am using react final form for validation purpose for login page which has forgot password and register link as well, now when I am clicking forgot password or register link ,it should not trigger any validation even though I am not filling my user name and password .I have tried t keep forgot password and register link away from tag but it is still triggering the validation on click of forgot password and register link .It should only trigger the validation when I m hitting submit button.
It should not ask to validate the form when I am clicking on any hyper link on the page as hyperlinks does not have any validations.
Here is the code sample
loginPage = () => {
const {t: translate} = this.props;
const {
match: {
params: {
authUrlKey = ''
} = {},
} = {},
} = this.props;
return (
<Form
onSubmit={ (values)=> this.validateUserCredentials(values)}
render={({ handleSubmit}) => (
<form onSubmit={handleSubmit}>
<button className="hidden" type="submit"/>
<h1 className="hw-block--pb">{translate('login.heading')}</h1>
<p className="hw-text-lead hw-block--pb-small">{translate('login.text')}</p>
{ this.state.description !=='' && <p className="hw-text-lead hw-block--pb-small">{this.state.description}</p> }
<div className="hw-grid">
<div className="hw-grid__item hw-one-whole hw-medium--one-fifth hw-large--one-sixth">
<label className="hw-label">{translate('login.landcode')}
<Field name="landcode" component={Dropdown} options={getCountryList()} onOptionSelect={this.onCountrySelect}/>
</label>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--four-fifths hw-large--five-sixths">
<label className="hw-label">{translate('login.mobileNumber')}
<Field type="text" component={InputType}
validate={composeValidators(mobileNumberRequired, validMobileNumberWithISDCode)}
placeholder={translate('login.mobileNumberPlaceHolder')} name="phoneNumber"/>
</label>
</div>
</div>
<label className="hw-label">{translate('login.password')}
<Field type="password" component={InputType} validate={passwordRequired} placeholder={translate('login.passwordPlaceHolder')} name="password"/>
</label>
<Link className="hw-link" to={{ pathname: '/password/reset', state: {authUrlKey} }}>{translate('login.forgotPassword')}</Link>
<ErrorInfo error={this.state.error} errorMessage={this.state.errorMessage} translate={translate}/>
<div className="hw-block hw-block--mt-small">
<div className="hw-grid">
<div className="hw-grid__item hw-small--one-whole hw-medium--one-quarter hw-block--mb-smaller">
<button className="hw-button hw-button--primary hw-button--full" type="submit">{translate('login.loginButton')}</button>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--three-quarters hw-block--mt-smaller">
<Link className="hw-link"
to={{ pathname: '/register', state: {authUrlKey} }}>{translate('login.registerButton')}</Link>
</div>
</div>
</div>
</form>)}
/>
)}
validations function used in code
export const validMobileNumberWithISDCode = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\+?((45)|(46)|(47))?( )?\d{8,10}$/
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const validMobileNumber = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\d{8,10}$/;
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const mobileNumberRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].mobileNumberRequired;
}
export const passwordRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined: message[root.lang].passwordRequired;
}
export const required =(fieldValue)=> {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].required;
}```
validateUserCredentials -> This function does not contains any validation.It is used to retrieve form values and send it to server
React Final Form calls your validation function on every value change in the form, to ensure that the form validity is always up to date. Since you did not include the code for your validation function, I cannot ascertain what you are attempting to do. Your validation function should be very cheap to run (e.g. required fields, value length, etc.). The actual authentication should happen on submit.
I made a simple faye tutorial application using this page:
http://code.tutsplus.com/tutorials/how-to-use-faye-as-a-real-time-push-server-in-rails--net-22600
And got a common problem with message displaying — server gets a parameter and renders it, but nothing happens on the page. I have alredy fixed faye.ru file, as was reccomended in comments. What should I do?
The most of the code is stored in a view:
<script>
$(function() {
// Subscribe to receive messages!
var client = new Faye.Client('http://localhost:9292/faye');
// Our public subscription
var public_subscription = client.subscribe('/messages/public', function(data) {
$('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
});
// Our own private channel
var private_subscription = client.subscribe('/messages/private/<%= session[:username] %>', function(data) {
$('<p></p>').addClass('private').html(data.username + ": " + data.msg).appendTo('#chat_room');
});
// Handle form submission to publish messages.
$('#new_message_form').submit(function(){
// Is it a private message?
if (matches = $('#message').val().match(/#(.+) (.+)/)) {
client.publish('/messages/private/' + matches[1], {
username: '<%= session[:username] %>',
msg: matches[2]
});
}
else {
// It's a public message
client.publish('/messages/public', {
username: '<%= session[:username] %>',
msg: $('#message').val()
});
}
// Clear the message box
$('#message').val('');
return false;
});
});
<div class="chat_container">
<div id="chat_room">
<p class="alert"> Welcome to the chat room <%= session[:username] %>! </p>
</div>
<form id="new_message_form">
<input type="text" id="message" name="message">
<input type="submit" value="Send">
</form>
</div>
Okay, I replaced "rails s thin" by "rails server thin" and, by some sort of magic, it has started working since
my cshtml file for upload, where would the javacsript go in this file?
#{
ViewBag.Title = "Upload";
}
<div id="progressbar">
<div id="progressbar" class="all-rounded" style="width: 20%"><span></span></div>
</div>
<div class="jumbotron">
<h2>Job Application Management System</h2>
<p class="lead2"> Welcome #((string)(ViewData["FullName"])), Please upload your resume here. Thank you!</p>
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td> <label> </label> <input type="file" class="btn btn-default" name="File" id="File" /></td>
</tr>
<tr>
<td><input type="submit" class="btn btn-default" id="upload" value="Upload" /></td>
</tr>
</table>
if (TempData["notice"] != null)
{
<p>#TempData["notice"]</p>
<p><button class="btn btn-default" onclick="location.href='#Url.Action("Create", "Accomplishments")';return false;">Continue To Accomplishments</button></p>
}
}
Here is my working code that shows how to accept a resume and save it using asp.net mvc
How do I post an error message stating that the file size is too large if the user submits a file that cannot be handled. Right now, if a user submits a file too large, it takes them to an errors page. I just want a popup or something on the screen that tells them to submit a file that is smaller. Thanks!
if (resume.File.ContentLength > 0)
{
string fileName = Path.GetFileName(resume.File.FileName);
string path = Path.Combine(Server.MapPath("~/Content/Resumes"), fileName);
resume.File.SaveAs(path);
}
TempData["notice"] = "Resume Added: "+ resume.File.FileName;
return View(resume);
}
catch (Exception)
{
ViewBag.Message = "Upload Error";
return View("Upload");
}
}
You can do this with simple javascript :
<script type="text/javascript">
$('#image-file').on('change', function() {
var filesize = this.files[0].size/1024/1024).toFixed(2) + " MB");
//Now can use use filesize variable and check it's value and show pop.
});
</script>
OR you can use this :
function GetFileSize(fileid) {
try {
var fileSize = 0;
//for IE
if ($.browser.msie) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //It will calculate file size in kb
// Put Your Alert or Validation Message Here
}
}
catch (e) {
alert("Error is :" + e);
}
}
Or you can check file size on form submit as:
<script type="text/javascript">
$(document).ready(function(){
$('#upload').on('click', function(e) {
e.PreventDefault();
var filesize = $("#File").files[0].size/1024/1024).toFixed(2)); //filesie in MB
//Now can use use filesize variable and check it's value and show pop.
if(parseInt(filesize)>3){ alert("File too large");return false; }
else{ $("form").submit(); }
});
});
</script>
I have a login page using jQuery Mobile which contains the following code:
<div id="loginPage" data-role="page" data-theme="a">
<div data-role="content">
<div id="alerts"></div>
<form id="login-form">
<input type="text" id="username" name="username" value="" placeholder="username or email" />
<input type="password" id="password" name="password" value="" placeholder="password" />
<button id="login-button" onClick="userLogin()">Login</button>
</form>
</div><!-- /content -->
</div><!-- /page -->
Here is a part of my javascript that is called when the user clicks the 'Login' button. If one of the fields is left blank, I see the following text injected into the #alerts div, but then within a fraction of a second the content has disappeared again.
if (username.length == 0 || password.length == 0) {
//alert('Please enter your username or email and your password');
$('#alerts').html('Please enter your username or email and your password.').trigger('create');
}
I also tried this using .append() instead of .html(). Same result with both. I've commented out my test alert(), which works when one of the fields is left blank.
What can I do to make sure the content remains on the page once it is injected?
Thank you for any help or insight you can offer! -Mark
Per Jasper's request, here is all of the javascript that is executed when the 'Login' button is clicked:
function userLogin() {
var username = $("#username").val();
var password = $("#password").val();
if (username.length == 0 || password.length == 0) {
$('#alerts').append('Please enter your username or email and your password.').trigger('create');
}
else {
$.post("services/user-status.php", { type: 'login', username: username, password: password },
function(data) {
var response = data.item;
console.log(response);
if (response.loggedIn == false) {
$('#alerts').html('The username/email and password you used did not work. Please try again.').trigger('create');
}
else {
localStorage.userID = response.userID;
localStorage.username = response.username;
localStorage.userStatus = 'loggedIn';
$.mobile.changePage('profile.html');
}
},'json');
}
}
It looks like you need to stop the propagation of the click event from firing for your button. You can do that by returning false in the click event handler:
HTML --
<button id="login-button" onClick="return userLogin()">Login</button>
JS --
function userLogin() {
...
return false;
}
Here is a demo: http://jsfiddle.net/BkMEB/3/
Also, since you are using jQuery, you can bind to the <button> element like this:
$('#login-button').bind('click', userLogin);
This is the same as putting onClick="return userLogin()" as an attribute of the button but allows you to remove your inline JS.
Here is a demo: http://jsfiddle.net/BkMEB/4/