如何使用AJAX将数据发布到php文件[重复]

如何使用AJAX将数据发布到php文件[重复]

问题描述:

This question already has an answer here:

I am having trouble sending data to a php file to be processed. I have tried just about everything but cannot find the source of the problem. Below is a php file that sends a product name, price, and ID to a checkout function after a user clicks on a buy button.

<?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();
    ?>

And next the checkoutfunction:

<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>

I am using MAMP's phpMyAdmin's database. Is my url incorrect? I've tried using "http://localhost:8888/checkout.php" and just checkout.php. Below is the php file where I need to process data. For simply learning how to send the data I am just echoing inside the file to make sure it is actually posting. But nothing is being echoed.

<?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;

 ?> 

I am new to web-programming so any help or tips would be appreciated. I've been looking at this for hours now and cannot seem to get it to work.

</div>

When using Ajax, the request is sent by ajax and you can see the response in the success method. Any direct call to the action URL will sends new request which is empty in this case for the line

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

Remove that line of code and change your jQuery.Ajax like bellow to see what's the response.

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 );
});

you should have following changes on your code

$.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.
Please 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.
' + jqXHR.responseText);
                    }
                 }
      });

You can track the ajax request in browser console. It will show you the request and response and the error you are receiving from your php script. If on button click you are not able to see any request in the console then try to use "method" instead of "type". Some older jquery version doesn't support type. method: "POST",

I tested your code and it worked, the ajax request occurs normally, try remove this single line from your javascript code. window.location.assign("http://localhost:8888/checkout.php");

I use this version of jQuery: https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js

In Network tab of Google Inspector I get this:

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

Response:
Bike150