如何通过$ .ajax发布发布JavaScript变量和HTML表单?

时间:2018-08-28 06:30:46

标签: javascript php jquery ajax post

我分别使用Ajax将两个javascript变量发布到php文件以及html表单中。我想将两个javascript变量与已发布的表单值一起使用,但不确定如何执行此操作。

<script>
   $(document).ready(function() {
      var aucid = "<?php echo $auctionID; ?>";
      var userid = "<?php echo $userID; ?>";
  $.ajax({
    url: "JqueryPHP/HighestBid.php",
    method: "POST",
    data: {'auctionid': aucid, 'userid' : userid },
    success: function (result) {
        $('#price').html(result);
    }
});


  $('form').bind('submit', function (event) {

 
event.preventDefault();// using this page stop being refreshing 



          $.ajax({
           type: 'POST',
            url: 'JqueryPHP/HighestBid.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });
        
        
  });

我将两个javascript变量分别发布到了表单上。

<form> 

<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control"  placeholder="New Bid €" value="" required>
 <input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
										                           
 </form>

<h4 class="price">Highest bid : <span id="price"></span></h4>

当我将userID的值回显到span类中时,您可以看到它的值为2。

enter image description here

//JqueryPHP/HighestBid.php'

$auctionid;
$userID;

  $auctionid = $_POST['auctionid'];
  $userID = $_POST['userid'];
  echo $userID;
  
  
  if (isset($_POST['newbid'])) 
  {
  $newbid=$_POST['newbid'];
 
  
    $conn = new mysqli('localhost', 'root', '', 'auctionsite');
 $sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
 if(@$conn->query($sql)){  //execute the query and check it worked    
                            return TRUE;
                        } 
         
  }

但是,当我在提交表单时尝试使用userID并尝试将其插入数据库以进行测试时,该值为0。

我该如何使用javascript变量发布表单值,以便可以使用更新语句来更新数据库?

enter image description here

4 个答案:

答案 0 :(得分:1)

设置两个隐藏的输入以保存auciduserid,如下所示:

<form> 

<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control"  placeholder="New Bid €" value="" required>
 <input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">

        <input name='aucid' style="display:none"/>  
        <input name='userid' style="display:none"/>                                                        
 </form>





<script>
    $(document).ready(function() {
          $("input[name='aucid']").val("<?php echo $auctionID; ?>");
          $("input[name='userid']").val("<?php echo $userID; ?>");

          .......................
    });
</script>

答案 1 :(得分:1)

假设您正确解析了变量,则可以使用:

$_POST['JavaScript_variable_name_goes_here'];

$_GET['JavaScript_variable_name_goes_here'];

根据您的AJAX方法检索PHP格式的变量。

您的AJAX函数的直接示例是:

<?php $auctionId=$_POST['auctionid']; ?>

但是,我鼓励您做的是,一旦用户登录,就将其userId设置为会话变量,您可以在用户“去”任何地方使用它。这样,您就不会通过JavaScript解析关键的数据元素,而JavaScript是在客户端处理的,这意味着用户可以通过使用浏览器开发工具来对其进行完全编辑。 AuctionId也是如此。出于完全相同的原因,我建议使用php会话变量逻辑。您始终可以根据另一个拍卖“正在使用”来用另一个AuctionId覆盖auctionId会话变量。

将userId设置为会话变量的另一个很好的理由是,只要您记得在开始时就设置以下内容,就可以在任何地方访问变量 不会有任何麻烦。 PHP文件:

<?php session_start(); ?>

mysqli_ *扩展的PHP / SQL语法如下:

$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);

让我知道您是否需要详细说明,或者遇到任何其他问题。

答案 2 :(得分:1)

将您的表单发送到php脚本。用户登录后,从数据库中检索其ID并将其置于会话中

 switch(isset($_POST['login'])):  
        case 'Register':
        $email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
        $password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');

        // check if the combination fname/lname/email is already used
        include('./Models/log_check.php');
        unset($_SESSION['ID'],$_SESSION['role']);
        $_SESSION['ID'] = $row['ID'];
        $_SESSION['role'] = $row['role'];

因此您可以在模型/查询中使用ID:

<?php
        /* Jointure sama RDV des vets */
        $query =
        "SELECT
        appointment.start,
        appointment.app_day,
        patients.pet_name,
        patients.breed,
        patients.ID,
        clients.last_name,
        clients.first_name,
        appointment.type,
        appointment.canceled
        FROM appointment
        JOIN patients
        JOIN clients
        WHERE clients.users_ID = patients.owner_ID
        AND patients.ID = appointment.patients_ID
        AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
        AND appointment.canceled = 'n'
        AND WEEK(appointment.app_day) = WEEK(:date)
        ORDER BY appointment.app_day,appointment.start";
        $query_params = array(':ID' => $_SESSION['ID'],
                                ':date' => $date);
        try {
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }catch(PDOException $ex){
            die("Failed to run query: " . $ex->getMessage());
        }
    ?>

插入而不是SELECT

答案 3 :(得分:0)

您可以在ajax调用中像这样将数据附加序列化

data: $("#form_id").serialize() + '&xyz=' + xyz