簡體   English   中英

在同一頁面中使用PHP和AJAX的最佳方法

[英]Best way to use PHP and AJAX in the same page

在同一頁面上,我有幾種類型的代碼:PHP,JS和HTML。 我想從HTML表單中獲取信息並進行PHP處理,而無需在單擊“發送”按鈕后重新加載頁面。

PHP獲取它通過API發送的值(來自表單),並在頁面上顯示API響應

HTML(首頁)

<form method="post">
  <input class="display-inline form-postcode" type="text" name="postcode" id="postcode" placeholder="Add your postcode for delivery estimate">
  <input class="form-postcode-submit" type="submit" value="Get estimate!">
</form>

PHP(第二個)

<?php
    if(isset($_POST['postcode'])) {
     $toPostcode = $_POST['postcode'];
}

// do stuff with $toPostcode
// use the API
// get response

echo $response;
?>

AJAX(第三篇 - 頁面底部)

<script>

function submitdata()
{
 var postcode = document.getElementById( "postcode" );

 $.ajax({
 type: 'post',
 data: {
 postcode:postcode
 },

  // ???

 });
}
</script>

我必須在同一個文件中使用PHP,因為我正在使用woocommerce,並且我在嘗試將文件放在外面時遇到很多錯誤

現在我想知道如何在同一頁面中使用所有這些

是的,您可以在同一頁面上使用。

您錯過了過程部分,例如:

success: function(){
      // code where you present the results
    }

您需要將PHP放在腳本的開頭。 當它看到postcode參數時,它可以返回AJAX響應然后exit ,而不顯示整頁的HTML。

所以看起來應該是這樣的:

<?php
if(isset($_POST['postcode'])) {
     $toPostcode = $_POST['postcode'];


    // do stuff with $toPostcode
    // use the API
    // get response

    echo $response;
    exit;
}
?>

<html>
<head>
    ...
</head>
<body>
    ...
    <form method="post" id="postcode-form">
      <input class="display-inline form-postcode" type="text" name="postcode" id="postcode" placeholder="Add your postcode for delivery estimate">
      <input class="form-postcode-submit" type="submit" value="Get estimate!">
    </form>
    ...
    <script>
    $(function() {
      $("#postcode-form").submit(function(e) {
        e.preventDefault();
        submitdata();
      });
    });

    function submitdata()
    {
     var postcode = document.getElementById( "postcode" );

     $.ajax({
     type: 'post',
     data: {
     postcode:postcode
     },

      // ???

     });
    }
    </script>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM