ReferenceError: stripeResponseHandler is not defined - FireFox - javascript

I am having an issue with using my Stripe connection in only Firefox, Chrome works perfect.
When I try to send card information to Stripe in Firefox (most recent) it tells me:
ReferenceError: stripeResponseHandler is not defined
Code:
<script type="text/javascript" src="../js/v2"></script>
.....
.....
// set publish key for stripe
Stripe.setPublishableKey('myToken');
// validate information
Stripe.card.createToken({
number: $('.cardnumber').val(),
cvc: $('.cw').val(),
exp_month: $('.expmonth option:selected').val(),
exp_year: $('.expyear option:selected').val(),
name: $(".cardholderfullname").val(),
address_line1: $(".address").val(),
address_city: $(".city").val(),
address_state: $("#state option:selected").val(),
address_zip: $(".zipcode").val()
}, stripeResponseHandler);
// error handling and success sending
function stripeResponseHandler(status, response) {
if (response.error) {
$("#message").fadeIn();
$("#message").html("The card information you entered was not valid, please check to make sure all information is correct.");
} else {
sendArray.token = response['id'];
$(sendArray).serialize();
//console.log(sendArray);
$.ajax({
type: "POST",
dataType: "JSON",
url: '../member/functions/stripeAcc/makeCustomer.php',
data: sendArray ,
success: function(response) {
}
});
closeDialogBox();
}
}
..... more
Suggestions and thoughts?

Related

How insert a id param in form ajax to be compatible with ie 11

I have a form to update data from a website that i am developing , and works fine on chrome, but on internet explorer 11 i recive a error of invalid character on the line of "chamadoid"
url: /chamados/${chamadoId},
whats is the proper way to set a id inside ajax url to make it work on ie?
function atualizarChamado() {
$(this).prop('disabled', true);
const chamadoId = $(this).data('chamado-id');
$.ajax({
url: `/chamados/${chamadoId}`,
method: "PUT",
data: {
nome: $('#nome').val(),
chamado: $('#chamado').val(),
ativocpu: $('#ativocpu').val(),
ativomonitor: $('#ativomonitor').val(),
endereco: $('#endereco').val(),
numero: $('#numero').val(),
cep: $('#cep').val(),
senha: $('#senha').val(),
transporte: $('#transporte').val(),
acionamento: $('#acionamento').val(),
status: $('#status').val(),
bairro: $('#bairro').val(),
obs: $('#obs').val(),
office: $('#office').val(),
ramal: $('#ramal').val(),
logindac: $('#logindac').val(),
re: $('#re').val(),
ativoretornomonitor: $('#ativoretornomonitor').val(),
ativoretornocpu: $('#ativoretornocpu').val(),
perifericomouse: $('#perifericomouse').val(),
perifericoteclado: $('#perifericoteclado').val(),
perifericohead: $('#perifericohead').val(),
perifericorede: $('#perifericorede').val(),
analistafield: $('#analistafield').val(),
gerenteoperador: $('#gerenteoperador').val()
}
}).done(function() {
Swal.fire('Sucesso!', 'Publicação criada com sucesso!', 'success').then(function() {window.location = `/chamados/${chamadoId}/editar`;})
}).fail(function() {
Swal.fire("Ops...", "Erro ao editar a publicação!", "error");
}).always(function() {
$('#atualizar-chamado').prop('disabled', false);
})
}
Just use + like that
// ...
url: '/chamados/' + chamadoId
// ...

using ajax with javascript to put in database

I'm trying to put the infos into my database, for that, this code is in the connexion.jsp which is a page that ask to log with facebook.
the code is supposed to be called into the Controller which is a file in java, and go into the databse.
So my problem is the fact that the code $.ajax doesn't seems to work. It doesn't give a success or error window.alert with or without function(){}.
I might have missed some information about ajax, but i can't find more info about my error.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
} else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
You have a syntax error in front of your else.

Make a Stripe payment with Jquery AJAX? (Javascript ONLY)

I am trying to make a custom payment form for Stripe, and I want to make the AJAX call to Stripe manually. (instead of a submit event)
However, first off I am pretty sure I am posting it to the wrong place. But I can't figure out what URL I'm supposed to make this post request to.
If I am using the right url. I am getting a 405 not allowed response. With no information on what is wrong with my request.
Here's what I got:
Stripe.setPublishableKey('pk_test_12345');
Stripe.card.createToken({
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
}, stripeResponseHandler);
This part works fine, gives me a 200 OK status and I got a token back from the server.
function stripeResponseHandler(status, response) {
console.log('card status: ', status);
console.log('token: ', response.id);
$.ajax({
type: 'POST',
url: 'https://checkout.stripe.com/checkout.js',
headers: {
stripeToken: response.id
},
data: {
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})
}
This however, gives me the 405 Not Allowed. It seems a bit weird to me that the endpoint would be a .js file. Which is why I am assuming I got the wrong URL.
Can anyone help me figure out how to make a manual post request for a Stripe payment?
Disclaimer: This works, but it is TERRIBLE practice. Don't use this for a real project. I needed it for a front-end only testing environment. As other users on this page has pointed out, you should be doing this on the backend!
I finally found some useful documentation at: https://stripe.com/docs/api#create_charge
As I suspected the URL I was using was wrong.
after getting the right URL, the following ajax call works:
Hope That helps someone else as well! As most answers, are PHP or other backend languages.
$.ajax({
type: 'POST',
url: 'https://api.stripe.com/v1/charges',
headers: {
Authorization: 'Bearer sk_test_YourSecretKeyHere'
},
data: {
amount: 3000,
currency: 'usd',
source: response.id,
description: "Charge for madison.garcia#example.com"
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})
EDIT: This is insecure (and outdated)! You shouldn't send your user's card information directly to your own server. Instead, you should directly send it to Stripe. There's an up-to-date (using intents, etc) example here
You need to POST to a PHP file in your $.ajax() function:
$.ajax({
type: 'POST',
url: './stripe-payment.php',
headers: {
stripeToken: response.id
},
data: {
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})
Your PHP should have something like the Stripe PHP bindings require()d to use the Stripe payment API, and that PHP file should look something like this, from this SO question:
<?php
require_once('Stripe.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account
Stripe::setApiKey("sk_test_APIKEYREDACTED");
// Get the credit card details submitted by the form
$token = json_decode($_POST['chargeData']);
$tokenid = $token['id'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
"amount" => 2000, // amount in cents, again
"currency" => "usd",
"card" => $tokenid,
"description" => "payinguser#example.com")
);
echo 'success';
} catch(Stripe_CardError $e) {
// The card has been declined
echo $tokenid;
}
?>
Refer to that Github's README for more, as well as the Stripe documentation.

jquery ajax call not returning as expected

I'm unsure why this jquery ajax call is failing. Basically, I want to authenticate and if the authentication is a success, do something.
I found this but the answer seems to abbreviated to be much use to me (is assumes you already know how to implement the solution). jQuery ajax return value
Here is my ajax call (I have stripped the fluff for getting the username/password):
function authenticate() {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
return "true";
} else {
return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
}
},
error:function(jqXHR, textStatus, errorThrown){
return "User failed to log into the system. Potential problem with server or connection.";
}
});
And I call it in this function:
function attemptEventSubmit(eKey) {
var authReturn = authenticate();
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
}
When it returns, it always alerts that authReturn is "undefined". I suspect it's defining authReturn as undefined because the authenticate function 'finishes' before the ajax call gets back...
But I'm not sure how to fix this problem.
I suspect I could call separate instead of returning values... (say, in this example, calling the emailEvent function directly in the ajax success function) but that would make the authenticate function specific... and it'd no longer be able to be used for authenticating for other purposes.
You can use your code but will need a callback. A better way would be look into promises.
function authenticate(onsuccess, onfail) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
onsuccess(data); // you should check if this is a function
},
error:function(jqXHR, textStatus, errorThrown){
onfail(errorThrown);
}
});
function attemptEventSubmit(eKey) {
authenticate(
function(ajaxData){
emailEvent('whatever you want to send');
},
function(errThrown){
alert(errThrown);
});
}
How about pass in a callback function as another argument of the function authenticate().
So the code changes will be
function authenticate(callback) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
//return "true";
callback("true");
} else {
//return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
callback("User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data);
}
},
error:function(jqXHR, textStatus, errorThrown){
//return "User failed to log into the system. Potential problem with server or connection.";
callback("User failed to log into the system. Potential problem with server or connection.");
}
});
Calling the function authenticate will become:
function attemptEventSubmit(eKey) {
authenticate(function(authReturn){
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
});
}

jQuery click handler not executing AJAX POST

Note: I personally prefer jQuery instead of $; it's more typing but I find it more readable.
I have a simple form that lets the user enter their first/last names and email address. It has a "Save" button, that, when clicked, executes:
jQuery('#saveButton').click(function() {
alert('About to Save to server');
var validated = validateContact();
if(!validated) {
alert('Did not validate!');
return;
} else {
alert('Validated!');
}
jQuery().ajax({
url: "saveContact",
type:"post",
dataType: 'json',
data: {
contact: {
firstName: jQuery('#firstName').val(),
lastName: jQuery('#lastName').val(),
emailAddress: jQuery('#emailAddress').val()
}
},
success: function(result) {
jQuery('#firstName').val("");
jQuery('#lastName').val("");
jQuery('#emailAddress').val("");
},
error: function(xhr){
alert(xhr.responseText);
}
});
alert('Saved to server');
});
When I click the "Save" button, I get several alert popups, including the "Validated!" message, however the script seems to die shortly after that, and I never see the "Saved to server" alert. This tells me my jQuery/AJAX call is bad. Furthermore, when I open my browser's Developer Tools, I don't see the browser actually making a network POST to my backend. In the console I don't see any errors. Any ideas as to where I'm going wrong and why I'm not even seeing any network activity?
Replace jQuery().ajax with jQuery.ajax({...})
Following Errors in your code:
Used jquery instead of jQuery.
Used jQuery() instead of jQuery in calling ajax method.
JS:
jQuery('#saveButton').click(function () {
alert('About to Save to server');
var validated = true; //Changed to temporary value.
if (!validated) {
alert('Did not validate!');
return;
} else {
alert('Validated!');
}
jQuery.ajax({ //Replaced jQuery() with jQuery
url: "/saveContact", //Sample URL
type: "post",
dataType: 'json',
data: {
contact: {
firstName: jQuery('#firstName').val(), //Replaced jquery with jQuery
lastName: jQuery('#lastName').val(), //Replaced jquery with jQuery
emailAddress: jQuery('#emailAddress').val() //Replaced jquery with jQuery
}
},
success: function (result) {
jQuery('#firstName').val(""); //Replaced jquery with jQuery
jQuery('#lastName').val(""); //Replaced jquery with jQuery
jQuery('#emailAddress').val(""); //Replaced jquery with jQuery
},
error: function (xhr) {
alert(xhr.responseText);
}
});
alert('Saved to server');
});
Demo: http://jsfiddle.net/lotusgodkk/x2mv94vm/6/

Categories

Resources