【问题标题】:Fetching Data from php to ajax从php获取数据到ajax
【发布时间】:2023-03-17 03:50:01
【问题描述】:

我在将数据从 ajax 发送到 php 时遇到问题,我需要一些帮助

$.ajax({
            type: "post",
            url: "/raffle.php",
            dataType: "json",
            data: {
                "postraffle": "true",
                "title": $("#rtitle").val(),
                "message": $("#mess").val(),
                "maxentry": $("#maxentry").val(),
                "duration": $("#durr").val(),
                "filter": $("#reffil").val(),
                "split": $("input[name=split]:checked").val(),
                "pub": $("input[name=rafflepub]:checked").val(),
                "stype": $("input[name=stype]:checked").val(),
                "invo": $("input[name=invo]:checked").val(),
                "items[]": itms,
                "games[]": gmes,
                },
            success: function(data){
                if(data.status == "fail")
                {   
                alert(data.message);
                $("#rafBut").removeAttr("disabled");
                $("#rafBut").attr("value", "Raffle it!");
                }
                else if(data.status == "ok")
                {
                alert(data.message);
                }

            }
        });

php 脚本在这里

    <?php

    // getting data from AJAX 
    $raffle_title = $_POST['title'];
    $raffle_message = $_POST['message'];
    $raffle_maxentry = $_POST['maxentry'];
    $raffle_duration = $_POST['duration'];
    $raffle_filter = $_POST['filter'];
    $raffle_split = $_POST['split'];
  $raffle_pub = $_POST['pub'];
  $raffle_stype = $_POST['stype'];


  $done = false;

  $data = array(
      'status' => 'ok',
      'message' => 'saved! redirecting you!',
      'datakey' => 'HALLEYO!',
  );

  $host ="localhost"; // enter your host.
  $pass =""; // enter your password.
  $db = "test"; // Enter your database..
  $user ="4"; // enter your username.

  # MYSQL Connection

  $con=mysqli_connect($host,$user,$pass,$db);
  if (mysqli_connect_errno($con))
  {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  foreach($_POST['items'] as $item){
    $query = "INSERT INTO table (heading,content,items) VALUES ('".$_POST['title']."', '".$_POST['message']."','".$item."')";
    // this should also be done for each item
    if (!mysqli_query($con, $query)) {
      printf("Error: %s\n", mysqli_error($con));
    }
  }

  echo $data;

  ?>

现在上述脚本的功能是从ajax获取数据并将其上传到mysql数据库,然后将响应发送回当前不起作用的ajax脚本。 我认为我的 mysql 查询可能有问题(php mysqli 参数化查询) 一些帮助将不胜感激。 谢谢!

【问题讨论】:

标签: php jquery mysql ajax mysqli


【解决方案1】:

你不能打印数组!

您必须将其 echo $data; 更改为 echo json_encode($data);

【讨论】:

  • 您好!感谢您的回复,但它没有在 mysql 中上传,并且消息没有在 ajax 中传输
【解决方案2】:

尝试替换

echo $data;

echo json_encode($data);

回显数据只会给出“数组”字符串,而不是任何 JSON 编码

【讨论】:

  • 您好!感谢您的回复,但它没有在 mysql 中上传,并且消息没有在 ajax 中传输
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2019-11-12
  • 2013-05-17
  • 2018-05-19
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
相关资源
最近更新 更多