简体   繁体   English

PHP表单(带有刷新)到AJAX(不带有刷新)

[英]PHP Form (with refresh) to AJAX (without refresh)

I have a piece of code that I'm wondering how I could go about converting to AJAX so the page doesn't refresh. 我有一段代码,我想知道如何才能转换为AJAX,这样页面就不会刷新。

At the moment, my script looks like this in design : https://gyazo.com/53be943f00fd372cab8555bc8ad7c1f2 目前,我的脚本设计如下: https : //gyazo.com/53be943f00fd372cab8555bc8ad7c1f2

Basically, the client types in a number (for the quantity), then they select 2 drop downs from the menus. 基本上,客户输入一个数字(代表数量),然后从菜单中选择2个下拉菜单。 They select what they have to trade and what they want from the trade. 他们选择要交易的商品以及从交易中获取的商品。 In my database, I make it check for the have and want and get the value from a row for the rate of the trade items. 在我的数据库中,我检查是否 需要,并从行中获取贸易商品价格的值。 I then do the rate * quantity to work out how much the trade will cost. 然后,我执行费率 * 数量来计算交易成本。

At the moment, my code is refreshing the page as it's done through PHP Form method. 目前,我的代码正在刷新页面,就像通过PHP Form方法完成的一样。 I want to convert this to ajax so it doesn't refresh the page. 我想将其转换为ajax,以便不刷新页面。

Can anyone help ? 有人可以帮忙吗?

My code is : 我的代码是:

    <form method="POST" action="#trading">
    <input type="hidden" value="<? echo $product_id; ?>" id="calc_name_<? echo $product_id; ?>">
    <input type="hidden" value="<? echo $product_rate; ?>" id="calc_rate_<? echo $product_id; ?>">

    <?php $query = mysqli_query($con, "SELECT * FROM tradable_items"); $query2 = mysqli_query($con, "SELECT * FROM tradable_items"); ?>

    <input type="text" class="form-control" name="quantity_input" style="background: white; border-radius: 5px; float: left; width: 24%; text-align: center;" placeholder="Quantity" required="">

    <select name="tradable_have" class="form-control" style="border-radius: 5px; float: left; width: 24%; text-align: center; margin-left: 15px;">
    <option>Select what you have</option>
    <?php 
        while ($row = mysqli_fetch_array($query)) {
            echo '<option value="'.htmlspecialchars($row['name']).'">'.$row['name'].'</option>';
        }
    ?>  
    </select>

    <select name="tradable_want" class="form-control" style="border-radius: 5px; float: right; width: 49%; text-align: center;">
    <option>Select what you want</option>
    <?php 
        while ($row = mysqli_fetch_array($query2)) {
            echo '<option value="'.htmlspecialchars($row['name']).'">'.$row['name'].'</option>';
        }
    ?>  
    </select>


<?php 
    if(isset($_POST['calculate_trade'])) {

        $item_name_have = $_POST['tradable_have'];
        $item_name_want = $_POST['tradable_want'];
        $item_quantity = $_POST['quantity_input'];

       $query_tradables = mysqli_query($con, "SELECT * FROM tradables WHERE name_from = '$item_name_have' AND name_to = '$item_name_want' LIMIT 1");

       while($row_tradable = mysqli_fetch_array($query_tradables)) {
            $product_item_rate = $row_tradable['price'];
       }

    ?>
        <input type="text" class="form-control" id="quantity_trader" style="background: #B5B5B5; border-radius: 5px; width: 100%; text-align: center;" readonly disabled placeholder="You will get: <?php echo $item_name_want; ?> (X<?php echo $item_quantity; ?>) for $<?php echo $item_quantity * $product_item_rate; ?>" required="">
    <?php
    } else {
    ?>
        <input type="text" class="form-control" id="quantity_trader" style="background: #B5B5B5; border-radius: 5px; width: 100%; text-align: center;" readonly disabled placeholder="What you will get" required="">
    <?php
    }
?>


<div class="pricing-table-cta">
    <button class="btn btn-default" type="submit" name="calculate_trade" style="width: 49%; float: left;">Calculate Trade</button>

    <?php 
        if(isset($_POST['calculate_trade'])) {
        ?>
            <a href="javascript:$zopim.livechat.say('I want to trade my <?php echo $item_name_have; ?> for your <?php echo $item_name_want; ?> in the quantity of <?php echo $item_quantity; ?> for the price of $<?php echo $item_quantity * $product_item_rate; ?>');" class="btn btn-default" style="width: 49%; float: right;">Order Now</a>
        <?php
        } else {
        ?>
            <button class="btn btn-default" disabled="" style="width: 49%; float: right;">Order Now (Calculate First)</button>
        <?php
        }
    ?>

</div>


</form>

Follow below steps. 请遵循以下步骤。

  1. Remove input type='submit' to type="button" 将输入type ='submit'删除为type =“ button”

  2. on click of that button get all the input values. 单击该按钮,即可获取所有输入值。 for example 例如

     $('.button').click(function(){ var inputData = $('form').serialize(); $.ajax({ url: url, type: 'POST', data:inputData, success: function (data) { Console.log(data) }, error: function (data) { } }); }); 

AJAX is designed for this type of task. AJAX专为此类任务而设计。

Basically, these things are what you need to do: 基本上,这些是您需要做的:

  • Remove the <form> tag and remove the type="submit" from submit button (To prevent page from normal submitting or refresh) 删除<form>标记,并从type="submit"按钮中删除type="submit" (以防止页面正常提交或刷新)
  • Attach event listener to the submit button which sends AJAX request 将事件监听器附加到发送AJAX请求的Submit按钮

This is what the code should looks like: 代码如下所示:

html: 的HTML:

<input type="text" name="quantity_input" id="quantity_input" />
<select name="tradable_have" id="tradable_have">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>
<select name="tradable_want" id="tradable_want">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>
<button id="submit-btn">Submit!</button>

javascript: javascript:

function callAjax()
{
  var xhttp = new XMLHttpRequest();
  var params = "quantity_input=" + document.getElementById("quantity_input").value;
  params += "&" + "tradable_have=" + document.getElementById("tradable_have").value;
  params += "&" + "tradable_want=" + document.getElementById("tradable_want").value;
  // parameters sent should be formatted like key1=value1&key2=value2 and so on
  xhttp.onreadystatechange = function()
  {
      if (this.readyState == 4 && this.status == 200)
      {
        // on response
        alert(this.responseText);
      }
  };
  xhttp.open("POST", "#", true);
  xhttp.send(params);
}

document.getElementById("submit-btn").addEventListener("click", callAjax);

or if you prefer jQuery: 或者,如果您更喜欢jQuery:

 $("#submit-btn").on("click", function(){
    $.ajax("#", {
       method: "post",
       data: {
           quantity_input: $("#quantity_input").val(),
           tradable_have: $("#tradable_have").val(),
           tradable_want: $("#tradable_want").val()
           // formatted like key1: value1, key2: value2 and so on
       },
       success: function(data){
           // on response
           alert(data);
       }
    });
 });

And to return calculated value from PHP to ajax is to use simple echo 要将计算值从PHP返回到ajax,是使用简单的echo

PHP (at the top of page): PHP(在页面顶部):

<?php

if(!empty($_POST)) // check if submitted or not
{
  echo calculate($_POST["quantity_input"]);
  exit; // echo only calculated, not html
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM