AJAX 变量传递给 SQL 但不传递给 PHP

Posted

技术标签:

【中文标题】AJAX 变量传递给 SQL 但不传递给 PHP【英文标题】:AJAX variable passes through to SQL but not PHP 【发布时间】:2020-03-22 08:24:43 【问题描述】:

我是 AJAX 的新手,如果有任何建议,我将不胜感激。

在一个文件中,我有以下 AJAX 代码:

        <meta charset="UTF-8">
      <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
      <script>


      var dyna = <?php echo $user_dyna; ?>;
      var limit = <?php echo $limit; ?>

      $(function() 

      $(".numbers-row").append('<div class="inc button" display:inline-block>+</div><div class="dec button">-</div>');

      $(".button").on("click", function() 

        var $button = $(this);
        var oldValue = $button.parent().find("input").val();

        if ($button.text() == "+") 
        if (dyna > 0) 
          var newVal = parseFloat(oldValue) + 5;
          dyna -= 5;
        
        else 
            newVal = oldValue;
        
         else 
           // Don't allow decrementing below zero
          if (oldValue > 0) 
            var newVal = parseFloat(oldValue) - 5;
            dyna += 5;
             else 
            newVal = 0;
          
          

        if (dyna >= 0) var dynatxt = dyna;
        else var dynatxt = 'Insufficient';

        $button.parent().find("input").val(newVal);

        var InstAtk = parseFloat(document.getElementById('atk').value);
        var InstDef = parseFloat(document.getElementById('def').value);
        var InstHP = parseFloat(document.getElementById('hp').value);
        var sum = InstAtk + InstDef + InstHP

        document.getElementById('dynacandy').innerhtml = '<b>Dyna Candies Remaining: ' + dynatxt + '</b>';

        if (sum > limit) 
        document.getElementById('limit').innerHTML = '<br><font color = "yellow">Stat total (' + sum + ') exceeds your limit of ' + limit + '</font><br>';
        
        else 
        document.getElementById('limit').innerHTML = '';
        
      );


        $(document).ready(function()   
            $("form").submit(function(event) 

            var Atk = document.getElementById('atk').value;
            var Def = document.getElementById('def').value;
            var HP = document.getElementById('hp').value;
            console.log(dyna);
            $.ajax(
            url: 'titan_ajax.php',
            type: 'POST',
            data: dyna: dyna, Atk: Atk, Def: Def, HP: HP,
            success: function(res)
                        console.log(res);
                        //alert('The server returned ' + res);
                    

            );
            );
        );

    );
      </script>

</head>

<body>
    <center>
    <div class="titan">
    <form method="post" action="titan_ajax.php">
     <div class="numbers-row">
         &nbsp;&nbsp;&nbsp;<label for="name">Dyna HP</label>
        <input type='number' name="hp" id="hp" value="<?=$titan['titan_hp']?>">
      </div>
     <div class="numbers-row">
        &nbsp;&nbsp;&nbsp; <label for="name">Dyna Attack</label>
        <input type="number" name="atk" id="atk" value="<?=$titan['titan_atk']?>">
      </div>
   <div class="numbers-row">
           &nbsp;&nbsp;&nbsp;&nbsp<label for="name">Dyna Defense</label>
        <input type="number" name="def" id="def" value="<?=$titan['titan_def']?>">
      </div>
      <br>
    <input type = "submit" button class = "global-btn" value="Submit">
    <br/>
    <br/>
    <span id="dynacandy"></span>
    <span id="limit"></span>
    <br>
    </form>
    </div>
    </center>
</body>

</html>

在我的 ajax 文件中,我有:

if (isset($_POST['dyna'])) 
    $newdyna = $_POST['dyna'];
    $newAtk = $_POST['Atk'];
    $newDef = $_POST['Def'];
    $newHP = $_POST['HP'];

    if ($newdyna < 0) 
        echo $newdyna;
        echo 'error';
    
    else 
        $mysqli->query("UPDATE user_items SET dyna_candy = $newdyna WHERE uid = $uid");
    

我得到的奇怪错误是 - SQL 工作得很好 - 我已经测试了十几次。但是,我永远无法回显 PHP 变量 $newdyna,也不会在 $newdyna 低于零时显示文本“错误”。每当 $newdyna

我在这里做错了什么?

【问题讨论】:

dyna_candy 是什么数据类型? 它是一个整数。 变量dyna 中保存的是什么值?在 JS 中尝试 console.log-ing 它,并在 PHP 端使用 var_dump(不是 echo)。我怀疑它是 PHP 中的null $newdyna = $_POST['dyna']; $newAtk = $_POST['Atk']; $newDef = $_POST['Def']; $newHP = $_POST['HP']; print_r 所有这些变量并查看输出 console.log dyna 在 ajax 中传递之前 【参考方案1】:

您的 ajax 无法正常工作我将您的代码移至新函数 sendToServer 尝试下面的 HTML 代码...

<html>
<meta charset="UTF-8">
      <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
      <script>


      var dyna = <?php $user_dyna=1; echo $user_dyna; ?>;
      var limit = <?php $limit=1; echo $limit; ?>;  

      $(function() 

          $(".numbers-row").append('<div class="inc button" display:inline-block>+</div><div class="dec button">-</div>');

          $(".button").on("click", function() 

            var $button = $(this);
            var oldValue = $button.parent().find("input").val();

            if ($button.text() == "+") 
            if (dyna > 0) 
              var newVal = parseFloat(oldValue) + 5;
              dyna -= 5;
            
            else 
                newVal = oldValue;
            
             else 
               // Don't allow decrementing below zero
              if (oldValue > 0) 
                var newVal = parseFloat(oldValue) - 5;
                dyna += 5;
                 else 
                newVal = 0;
              
              

            if (dyna >= 0) var dynatxt = dyna;
            else var dynatxt = 'Insufficient';

            $button.parent().find("input").val(newVal);

            var InstAtk = parseFloat(document.getElementById('atk').value);
            var InstDef = parseFloat(document.getElementById('def').value);
            var InstHP = parseFloat(document.getElementById('hp').value);
            var sum = InstAtk + InstDef + InstHP

            document.getElementById('dynacandy').innerHTML = '<b>Dyna Candies Remaining: ' + dynatxt + '</b>';

            if (sum > limit) 
                document.getElementById('limit').innerHTML = '<br><font color = "yellow">Stat total (' + sum + ') exceeds your limit of ' + limit + '</font><br>';
            
            else 
                document.getElementById('limit').innerHTML = '';
            
      );

    );



    function sendToServer() 
        var Atk = document.getElementById('atk').value;
        var Def = document.getElementById('def').value;
        var HP = document.getElementById('hp').value;
        console.log(dyna);
        $.ajax(
            url: 'titan_ajax.php',
            type: 'POST',
            data: dyna: dyna, Atk: Atk, Def: Def, HP: HP,
            success: function(res)
                alert('success');
                console.log(res);
            ,   
             error: function (jqXHR, exception) 
                var msg = '';
                if (jqXHR.status === 0) 
                    msg = 'Not connect.\n Verify Network.';
                 else if (jqXHR.status == 404) 
                    msg = 'Requested page not found. [404]';
                 else if (jqXHR.status == 500) 
                    msg = 'Internal Server Error [500].';
                 else if (exception === 'parsererror') 
                    msg = 'Requested JSON parse failed.';
                 else if (exception === 'timeout') 
                    msg = 'Time out error.';
                 else if (exception === 'abort') 
                    msg = 'Ajax request aborted.';
                 else 
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                
                alert(msg);
            

        );
        return false;
    
</script>

</head>

<body>
    <center>
    <div class="titan">
    <form method="post" onsubmit="sendToServer();">
         <div class="numbers-row">
             &nbsp;&nbsp;&nbsp;<label for="name">Dyna HP</label>
            <input type='number' name="hp" id="hp" value="<?=$titan['titan_hp']?>">
          </div>
         <div class="numbers-row">
            &nbsp;&nbsp;&nbsp; <label for="name">Dyna Attack</label>
            <input type="number" name="atk" id="atk" value="<?=$titan['titan_atk']?>">
          </div>
       <div class="numbers-row">
               &nbsp;&nbsp;&nbsp;&nbsp<label for="name">Dyna Defense</label>
            <input type="number" name="def" id="def" value="<?=$titan['titan_def']?>">
          </div>
          <br>
        <input type = "submit" button class = "global-btn" value="Submit">
        <br/>
        <br/>
        <span id="dynacandy"></span>
        <span id="limit"></span>
        <br>
    </form>
    </div>
    </center>
</body>

</html>

【讨论】:

您好 Ronak,感谢您提出的解决方案!然而,我正在寻找的是一个页面,它会在点击提交按钮后通过表单操作将用户重定向。 我试图根据我的 titan_ajax.php 文件中的条件向用户显示“成功”或“失败”消息。例如,如果 $newdyna 是的,上面的代码不会重定向,只用ajax做事 是的,您的代码在 ajax 中工作。但我想知道如何显示如上所述的“成功”或“失败”消息。【参考方案2】:

通过添加到 Ronak 的原始 sendtoServer() 函数,我设法找到了解决我的问题的方法。此方法不涉及页面重定向,但仍显示在我的 titan_ajax.php 中回显的成功/错误消息。

function sendToServer() 
    event.preventDefault();

    console.log(change);
    console.log(dyna);

    $.ajax(
        url: 'titan_ajax.php',
        type: 'POST',
         data: dyna: dyna, Atk: Atk, Def: Def, HP: HP,
        success: function(res)
            console.log(res);
           

    );

        $(".form-message").load("titan_ajax.php", 
        dyna: dyna,
        Atk: Atk,
        Def: Def,
        HP: HP,
        );
        return false;
    

在我的 html 中,我添加了以下标签来显示来自 'titan_ajax.php' 的回声:

<p class="form-message"></p>

【讨论】:

以上是关于AJAX 变量传递给 SQL 但不传递给 PHP的主要内容,如果未能解决你的问题,请参考以下文章

PL/SQL:, 如何将变量传递给 SELECT 语句并返回所有结果行

Laravel 使用 AJAX 将 Javascript 变量传递给 PHP 并检索那些

通过 ajax 将 Javascript 变量传递给 PHP

将 AJAX 变量传递给 PHP

将全局变量传递给ajax函数,发布到php,保存到数据库

无法使用 AJAX 将 JS 变量传递给 PHP