如何使用AJAX将数据发布到php文件

时间:2016-04-21 03:13:03

标签: javascript php ajax phpmyadmin

我无法将数据发送到要处理的php文件。我已经尝试了几乎所有但是找不到问题的根源。下面是一个php文件,在用户点击 buy 按钮后,会向checkout函数发送产品名称,价格和ID。

<?php

      $servername = "localhost";
      $username = "root";
      $password = "root";
      $dbname = "Test";

        // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);

        // Check connection
      if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
     } 

     $sql = "SELECT P1.Product_Name, S2.Price, P1.Product_ID FROM Product P1, Sale_Item S2 WHERE P1.Product_ID=S2.Product_ID AND P1.Category='Sports'";
     $res = $conn->query($sql);
     $counter=0;

     while ($row = $res->fetch_assoc()){

      $Product_Name = $row["Product_Name"];
      $Price = $row["Price"];
      $Product_ID = $row["Product_ID"];

      echo ('<td><p></p>'.$row["Product_Name"].'<br>'.$row["Price"].'<p></p><input type="button" value="Buy" onclick="checkout(\'' . $Product_Name . '\', \'' . $Price . '\', \'' . $Product_ID . '\')"</td>');          
      $counter++;

      if ($counter==3) {
        $counter=0;
        print "<br>";
      }
    }

    $conn->close();
    ?>

然后是checkout函数:

<script type="text/javascript">
        function checkout(Product_Name, Price, Product_ID) {
          //document.write(Product_Name, Price, Product_ID)
          var theProduct_Name = Product_Name;
          var thePrice = Price;
          var theProduct_ID = Product_ID;

          $.ajax({
            type: "POST",
            url: "http://localhost:8888/checkout.php",
            data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
          });

          window.location.assign("http://localhost:8888/checkout.php")
        }
      </script>

我正在使用MAMP的phpMyAdmin数据库。我的网址不正确吗?我尝试过使用"http://localhost:8888/checkout.php"checkout.php。下面是我需要处理数据的php文件。为了简单地学习如何发送数据,我只是回显文件内部以确保它实际发布。但没有任何回应。

<?php 

  session_start();
  $servername = "localhost";
  $username = "root";
  $password = "root";
  $dbname = "Test";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 } 

  $theProduct_Name = $_POST['Product_Name'];
  $theProduct_ID = $_POST['Product_ID'];
  $thePrice = $_POST['Price'];

 echo $theProduct_Name.$theProduct_ID.$thePrice;

 ?> 

我是网络编程的新手,所以任何帮助或提示都会受到赞赏。我一直在看这几个小时,似乎无法让它发挥作用。

4 个答案:

答案 0 :(得分:2)

使用Ajax时,请求由ajax发送,您可以在success方法中看到响应。对行动URL的任何直接调用都将发送新请求,在这种情况下该行为空

window.location.assign("http://localhost:8888/checkout.php")

删除那行代码,然后像下面那样更改你的jQuery.Ajax以查看响应的内容。

var request = $.ajax({
    type: "POST",
    url: "http://localhost:8888/checkout.php",
    data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
    dataType: "html"
});

request.done(function(msg) {
  alert ( "Response: " + msg );
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

答案 1 :(得分:0)

您应该对代码进行以下更改

$.ajax({
        method: "POST",
        url: "http://localhost:8888/checkout.php",
        data: {"Product_Name": "theProduct_Name", "Price": "thePrice", "Product_ID": "theProduct_ID"},
        success : function(responseText)
                  {
                    alert('success to reach backend');
                    // you can console the responseText and do what ever you want with responseText
                    console.log(responseText);
                  },
        error : function(jqXHR, status, error){
                    if (jqXHR.status === 0) {
                        alert('Not connected.\nPlease verify your network connection.');
                    } else if (jqXHR.status == 404) {
                        alert ('The requested page not found. [404]');
                    } else if (jqXHR.status == 500) {
                        alert ('Internal Server Error [500].');
                    } else if (exception === 'parsererror') {
                        alert ('Requested JSON parse failed.');
                    } else if (exception === 'timeout') {
                        alert ('Time out error.');
                    } else if (exception === 'abort') {
                        alert ('Ajax request aborted.');
                    } else {
                        alert ('Uncaught Error.\n' + jqXHR.responseText);
                    }
                 }
      });

答案 2 :(得分:0)

您可以在浏览器控制台中跟踪ajax请求。它将向您显示请求和响应以及您从PHP脚本收到的错误。 如果单击按钮,则无法在控制台中看到任何请求,请尝试使用“方法”而不是“类型”。一些较旧的jquery版本不支持类型。 method: "POST",

答案 3 :(得分:0)

我测试了你的代码并且它工作正常,ajax请求正常发生,尝试从你的javascript代码中删除这一行。 window.location.assign(&#34; http://localhost:8888/checkout.php&#34);

我使用这个版本的jQuery:https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js

在Google Inspector的“网络”标签中,我得到了这个:

Request:
Request URL:http://localhost:8888/checkout.php
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:8888

Response:
Bike150