Why does Stripe's handleCardPayment not run in my Javascript function? - javascript

I am trying to use Stripes handleCardPayment to process a charge following a payment intent. I can't get the handleCardPayment function to run inside another Javascript function.
I have tried to debug my code step by step. The Javascript function runs and will print out an alert to the window.
The Javascript variables I set at the top of the function also get set.
The handleCardPayment() function however does not seem to run?
I have attempted a try/catch to see if I can catch the error coming from the request but nothing is logged.
I am a little stumped as to where the issue is with this? although I suspect it might be something basic that I am missing on calling the stripe function correctly.
function completePayment() {
// Assign client secret from PHP session variable
var clientSecret = "<?php echo $_SESSION['c_secret'] ?>";
try {
stripe.handleCardPayment(
clientSecret, cardElement, {
source_data: {
owner: {email: "<?php echo $_SESSION['m_usr_email'] ?>"}
}
}
).then(function(result) {
if (result.error) {
alert("Error in payment");
} else {
alert("Success in payment");
}
});
}
catch(error) {
console.log(error.message);
}
}
My payment intent is created on a separate PHP page. This works correctly and a payment intent is created in stripe with an associated client secret.
How the app currently functions:
User presses 'Subscribe' button.
Ajax request runs and POSTS to a separate PHP file
PHP file creates the payment intent and saves the client secret in a PHP SESSION variable
Ajax 'Complete function()' then calls 'completePayment();'
Javascript function 'completePayment();' is located just before the closing tag at the bottom of the page.
Debugging 'completePayment()' shows that the function does execute following the Ajax 'Complete function()' call.
stripe.HandleCardPayment fails to do anything.
cardElement is a global Javascript variable set when the card element is created (this is created on initial page load).
I have debugged both PHP SESSION variables and confirm that they have both been set with the correct information prior to using them in the handleCardPayment function.
Any suggestions on what I am doing wrong here?

I had same problem. It looks like the function it does not execute becouse the console logs does not appear but after searching I saw that I missing $intent->client_secret, before that, the js console not show me anything and I had to call only the function stripe.handleCardPayment without any code extra then the cosole show me $intent->client_secret It was undefined.
I don't speak english very well I hope that It will serve somebody

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

undefined result javascript

I have a simple javascript code, that validate when you write a order number and generates tags with javascript(with bootstrap-tagsinput js):
var order = $('#order_number').val();
if ($.inArray(order, $('#input_order_tags').val()) >= 0) {
$('#input_order_tags').tagsinput('add', order);
return;
}
var params = {
email: email,
order_code: order
}
AjaxServices.validateOrderNumberByEmail(params, function(error, result) {
if (error)
alert(error);
else
$('#input_order_tags').tagsinput('add', result.order);
});
This works fine but, every time trigger the error message when send a order number:
Console chrome debug:
How I can avoid the error of alert?
This is not a javascript issue. Server-side in you application you use order_code in one of the calls which returns the error message you see in the ajax call. Debug the offending call server-side, see which call returns that error and adjust your code so it works properly.
There might be two possibilities
client side issue ( javascript error) if so, its because the field order_number is disabled field.
as mentioned in this link
undefined index on javascript dynamic variables when passing to php form
If so, remove that disabled and use read-only and check if it works, without any error.
Server side issue( ajax call) if so, server side code which performs on call of that ajax call is causing that issue.

Javascript runtime error: 'processPartInput' is undefined

I am trying to retrieve data from a controller. This is a new twist on my Json error. I added a function to the index.cshtml page and I try to add code to get the information from the controller. I added a basic code to write a string to the textbox (all local) and that worked. When I tried to call from the controller it doesn't matter what the code is I get this error:
(source: mousecreations.com)
I have tried the following with the same error. Probably some other combinations that I have found in my search.
$.getJSON(#Url.Action("GetIPAddress","getipaddress"),
$.get(......)
$.ajax(......)
The entire function
function processgetip(event)
{
// Within this function, make an AJAX call to get the IP Address
$.getJSON(#Url.Action("GetIPAddress","getipaddress"), function (ip) {
// When this call is done, your IP should be stored in 'ip', so
// You can use it how you would like
// Example: Setting a TextBox with ID "YourElement" to your returned IP Address
$("#facility").val(ip);
});
}
This error is different than any of the others so what in that process event would cause the other processes to be undefined?

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Categories

Resources