0

In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.

The PHP page:

$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);

Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.

<?php
$IDToPassPlus = ($id.'&retid=');
?>


<script>

//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid; 
},
});


paypal.Button.render({
env: 'sandbox',

client: {
sandbox:    'xxxxx',
production: 'xxxxx'
},

commit: true,

style: {
layout: 'vertical',
size:   'responsive',
shape:  'rect',
color:  'gold'
},

payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},


onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},

onCancel: function(data, actions) {
return actions.redirect();
},

onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}

}, '#paypal-button');


</script>

Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.

imagina
  • 65
  • 1
  • 6
  • Are you using page javascript or on a separate page? – Mohsin A. Mar 27 '18 at 18:34
  • The PHP and JS are on different pages – imagina Mar 27 '18 at 18:35
  • you can not call PHP variable in .js files but you can set PHP variable to an HTML dom element and then from javascript you can read it. – Mohsin A. Mar 27 '18 at 18:38
  • for example: `` you can read its data as : `var x = $('meta[name="_token"]').attr('content')` – Mohsin A. Mar 27 '18 at 18:40
  • So you're now working on learning ajax, which is a good next step. Before you try to integrate ajax with something complicated like Paypal's checkout process (which makes it very hard for other people to help you, since that process is not known to most folks), start with a simpler ajax example. Start with a very simple/test page where you use ajax to echo $username to the page, after a simple button click. Once you can do that, then you can do the slightly more complicated code you have here. – KayakinKoder Mar 28 '18 at 14:06
  • For example, below you say "placing it inside my Paypal script stops the pay button from working". But you haven't told us *why* it doesn't work. Are there console errors? Is retid undefined when the pay button is clicked? Are there any html related errors? Etc. Start by learning how to get a simple ajax call to return a value and print that value to the page, after a basic – KayakinKoder Mar 28 '18 at 14:08
  • Is this .js or .php page? As I can see you are using `` Confusing... If its PHP page then why not use $_GET, $_REQUEST or $_SESSION to share data? – Mohsin A. Mar 28 '18 at 15:15
  • It's PHP in HTML, which also includes javascript. Somewhere in the javascript part I need to make an AJAX call to a _different_ PHP page to retrieve some data, then assign that data to a javascript variable "retid", and use it in the javascript (as the appended query string value to the `window.location.replace` URLs). The PHP variable `$IDToPassPlus` is just including the initial variable in the query string and then preparing the appending of the `retid` javascript variable. – imagina Mar 28 '18 at 16:17

3 Answers3

0

it's possible to use on in-page javascript as

<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page

If it's not what you are seeking, then please elaborate your question.

Mohsin A.
  • 98
  • 1
  • 5
  • I'm trying to pass the data from the first PHP page to the second page and capture it in that second page via ajax as a javascript variable It's the AJAX javascript code for the second page that I'm not clear on. – imagina Mar 27 '18 at 18:38
  • This is asking how to pass the json output from a PHP page to another page - how to use ajax in a javascript to capture that variable. – imagina Mar 27 '18 at 18:45
0

ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:

$.ajax({
               type: 'POST',
               url: 'YOUR PHP SCRIPT URL',

               dataType: 'json',//this will make it understand what datatype to expect in response
               success: function(response) {
                    var retid = response.data.retid; //here you get on successfull response
               },
             });
Mohsin A.
  • 98
  • 1
  • 5
0

First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve

Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:

$.ajax({
    type: 'POST',
    url: 'test-call.php',
    dataType: 'json',
    success: function(response) {
        var retid = response.data.retid;
        console.log(retid);
    },
});

This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?

So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.

(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)

(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)

KayakinKoder
  • 3,243
  • 3
  • 23
  • 37
  • I have been doing the snippets alone first. Trying the code above shows a 404 in the console – imagina Mar 28 '18 at 14:25
  • Ok great, so now we know *something*, this is much better than just "it's not working". A 404 error means file not found, right? And what file is not found? Probably test-call.php So it would seem that our `url` definition in the $.ajax call is incorrect – KayakinKoder Mar 28 '18 at 14:28
  • Which is odd because if I dispense with JSON output from test-call.php and just output a string from there instead, this will work: ``. In other words `retid` is returned and outputs. But I don't see a way to introduce this code into the PayPal code without breaking it either. – imagina Mar 28 '18 at 14:43
  • Though I still get the 404 with the succeeding code. – imagina Mar 28 '18 at 14:55
  • You definitely want to use an $.ajax request; working on figuring out this 404 is your next step. Do some searching on stackoverflow for "ajax file location", you should find what you need. If you read and research and try different things and can't get it to work after trying hard on your own, you know the drill :) Create a new stackoverflow question in MCVE format – KayakinKoder Mar 28 '18 at 14:59