php中函数的Ajax连接失败

Ajax connection to function in php failing

本文关键字:连接 失败 Ajax 函数 php      更新时间:2023-09-26

我试图通过ajax提交表单,但它不允许我:

Ajax-同页

<script type="text/javascript">
  $(document).on('submit','.subscribe',function(e) {
  $.ajax({ url: 'lib/common-functions.php',
     data: {action: 'subscribe'},
     type: 'post',
     success: function(output) {
                  alert(output);
              }
     });
  });
</script>

HTML-同页

  <form class="subscribe">
    <label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
    <label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail" > 
    <input type="submit" id="ssub" value="Subscribe">
  </form>

PHP-通用功能.pp

<?php
  require_once('dbconn.php');
  function subscribe() {
    $name = $_POST['sname'];
    $email = $_POST['semail'];
    $db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ($sname, $email, 0)");
    echo "You have been subscribed";
  }
?>

编辑添加的dbconn

$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
  echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}

在控制台里,我什么也得不到。在我点击提交并检查控制台之后。我可以用红色看到如何操作common-functions.php,但什么都不做。请帮忙。

TL;DR您需要做六件事来修复您提供的代码中的问题。事件传播、作用域和变量验证存在缺陷。

首先将其添加到您的JavaScript:event.preventDefault(); event.stopPropagation();中。

第二步,提交您的实际数据。

显示这些修复的示例:

$(document).on('submit','.subscribe',function(e) {
    e.preventDefault(); // add here
    e.stopPropagation(); // add here
    $.ajax({ url: 'lib/common-functions.php',
        data: {action: 'subscribe',
            sname: $("#sname").val(),
            semail: $("#semail").val()},
        type: 'post',
        success: function(output) {
            alert(output);
        }
     });
});

第三,实际调用subscribe()

第四个,您有一个作用域问题:$db是全局的,但您没有将其称为全局的。这就是我在下面添加global $db;的原因。

第五步,检查POST值是否存在。

第六步,在数据库值周围加引号,然后先转义。

<?php
require_once('dbconn.php');
function subscribe() {
    global $db;
    if(isset($_POST['semail'], $_POST['sname'])) {
        $name = $_POST['sname'];
        $email = $_POST['semail'];
        $db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($sname)."', '".$db->escape_string($email)."', 0)");
        echo "You have been subscribed";
    }
}
subscribe();
?>

注意:这只是展示了如何修复您发布的代码。然而,问题中的代码对SQL注入是完全开放的。您确实应该使用已准备好的语句,而不是依赖于特殊字符的转义。

您必须将通过PHP中的Post访问的数据包含在$.ajax调用的数据对象中:

$.ajax({ url: 'lib/common-functions.php',
 data: {action: 'subscribe',
        sname: $("#name").val()
        semail: $("#semail").val()},
 type: 'post',
 success: function(output) {
              alert(output);
          }
 });

});

此外,您的PHP函数subscribe不会仅通过设置action来调用:"subscribe"您必须检查$_POST["action"]是否为"subscribe":

if($_POST["action"]=="subscribe")
{
    subscribe();
}