最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript retrieve fetch response from a php - Stack Overflow

matteradmin6PV0评论

I'm try to implement the paypal express checkout. So I implement the button and write the result in my database. Nothing exceptional, it's the script they gave.

<script>
paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        // Call your server to save the transaction
        return fetch('recordDatabase.php', {
          method: 'post',
          mode: "same-origin",
          credentials: "same-origin",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify({
              orderID: data.orderID, 
              time: details.create_time, 
              status: details.status, 
              nom: details.payer.name.given_name, 
              prenom: details.payer.name.surname, 
              pays: details.payer.address.country_code, 
              valeur:details.purchase_units[0].amount.value
          })
        })
      });
    }
  }).render('#paypal-button-container');
</script>

The php to record in the database:

<?php
$link = connect();

$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';

if ($contentType === "application/json") {
    //Receive the RAW post data.
    $content = trim(file_get_contents("php://input"));
    $decoded = json_decode($content, true);

    //If json_decode failed, the JSON is invalid.
    if(! is_array($decoded)) {
        //echo "error";
    } else {
        $name = $decoded['nom'];
        $time = $decoded['time'];
        $id = $decoded['orderID'];
        $stat = $decoded['status'];
        $pays = $decoded['pays'];
        $val = $decoded['valeur'];

        $secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email@mail','$id','$stat','$name','$pays','$val') ";
        if (mysqli_query($link,$secQuery)) {
            //echo "ok";
        } else {
            //echo "error";
        }

    }
} else {
    //echo "error";
}

So, the record in my database works fine, but my question is:

How can I retrieve the echo error or ok in the javascript to confirm the user that everything is fine, or if an error happen.

I tried another solution, to redirect the user from the php and add to the php:

header("Location: confirmation web page"); or
echo "<script>window.location = 'confirmation web page'</script>";

but both solution doesn't work. No redirection happen

I'm try to implement the paypal express checkout. So I implement the button and write the result in my database. Nothing exceptional, it's the script they gave.

<script>
paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        // Call your server to save the transaction
        return fetch('recordDatabase.php', {
          method: 'post',
          mode: "same-origin",
          credentials: "same-origin",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify({
              orderID: data.orderID, 
              time: details.create_time, 
              status: details.status, 
              nom: details.payer.name.given_name, 
              prenom: details.payer.name.surname, 
              pays: details.payer.address.country_code, 
              valeur:details.purchase_units[0].amount.value
          })
        })
      });
    }
  }).render('#paypal-button-container');
</script>

The php to record in the database:

<?php
$link = connect();

$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';

if ($contentType === "application/json") {
    //Receive the RAW post data.
    $content = trim(file_get_contents("php://input"));
    $decoded = json_decode($content, true);

    //If json_decode failed, the JSON is invalid.
    if(! is_array($decoded)) {
        //echo "error";
    } else {
        $name = $decoded['nom'];
        $time = $decoded['time'];
        $id = $decoded['orderID'];
        $stat = $decoded['status'];
        $pays = $decoded['pays'];
        $val = $decoded['valeur'];

        $secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email@mail','$id','$stat','$name','$pays','$val') ";
        if (mysqli_query($link,$secQuery)) {
            //echo "ok";
        } else {
            //echo "error";
        }

    }
} else {
    //echo "error";
}

So, the record in my database works fine, but my question is:

How can I retrieve the echo error or ok in the javascript to confirm the user that everything is fine, or if an error happen.

I tried another solution, to redirect the user from the php and add to the php:

header("Location: confirmation web page"); or
echo "<script>window.location = 'confirmation web page'</script>";

but both solution doesn't work. No redirection happen

Share Improve this question edited Jul 23, 2023 at 13:55 EML 10.3k8 gold badges49 silver badges85 bronze badges asked Feb 21, 2019 at 17:31 laurent eminlaurent emin 271 gold badge1 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Correct if i'm wrong, recordDatabase.php is your php file that is storing the transactions.

So, the return fetch('recordDatabase.php', { is returning the response from this file, your echo 'ok';,echo 'error';, the fetch is asyncronous, so it'will return a promise.

Add header('Content-Type: application/json'); to your php file so it returns a json response. Also change your echo to echo '{"status":"ok"}'; and echo '{"status":"error"}';

Now modify your fetch function,

return fetch('recordDatabase.php', {
     //same info here
})
.then((response) => response.json())
.then((responseData) => {
      if(responseData.status == "ok"){
           alert("it worked");
      }else{
           alert("it didn't work");
      }
})

I have just solved your case , just try this code and see how it works Paypal Script API

<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        alert('Transaction pleted by ' + details.payer.name.given_name+' ApplicationId <?php echo $id; ?> :payerID'+data.payerID);

        // Call your server to save the transaction
        return fetch('payments.php', {
          method: 'post',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
              orderID: data.orderID, 
              time: details.create_time, 
              status: details.status, 
              nom: details.payer.name.given_name, 
              prenom: details.payer.name.surname, 
              pays: details.payer.address.country_code, 
              valeur:details.purchase_units[0].amount.value
          })
        }).then(data => data.ok && data.json()).then(response => {
            alert(response.status);
        });         
      });
    }
  }).render('#paypal-button-container');
</script>

PHP script (payments.php)

 <?php
    header('Content-Type: application/json');

$date = date('Y-m-d H:i:s');
    //Receive the RAW post data.
    $contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';

    if ($contentType === "application/json") {
        //Receive the RAW post data.
        $content = trim(file_get_contents("php://input"));
        $decoded = json_decode($content, true);

        //If json_decode failed, the JSON is invalid.
        if(! is_array($decoded)) {
            //echo "error";
        } else {
            $name = $decoded['nom'];
            $time = $decoded['time'];
            $id = $decoded['orderID'];
            $stat = $decoded['status'];
            $pays = $decoded['pays'];
            $val = $decoded['valeur'];

          echo '{"status":"ok"}';

        }
    } else {
        echo '{"status":"error"}';
    }

    ?>

return fetch('codes/paypalapi.php', { method: 'post', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ orderID: data.orderID })
});

it will work perfectly i had the same situation

Post a comment

comment list (0)

  1. No comments so far