dongtazu3080 2019-02-21 17:31 采纳率: 100%
浏览 45
已采纳

javascript从php检索获取响应

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

  • 写回答

1条回答 默认 最新

  • donglong1465 2019-02-21 19:32
    关注

    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");
          }
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制