5

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sam5487
  • 669
  • 1
  • 6
  • 14
  • You should not expect to see anything echo out by calling the action url directly. You're sending Ajax and it return response back to it. – Navid Apr 21 '16 at 03:29
  • @MateHegedus Would a better approach be to use a form that directly sends the data to a php file, instead of sending it to a function first then using AJAX? – Sam5487 Apr 21 '16 at 03:29
  • @NMoeini I know, but when I call ` window.location.assign(`"http://localhost:8888/checkout.php"`) ` after the ajax returns, shouldn't the data be echoed? – Sam5487 Apr 21 '16 at 03:31
  • Nope. Because it sends nothing in the second call. The request is empty on the second call. – Navid Apr 21 '16 at 03:33
  • @NMoeini So the code should be working, I'm just not seeing it? How can I verify that my data is being posted? – Sam5487 Apr 21 '16 at 03:37
  • Added my answer. Try it. – Navid Apr 21 '16 at 04:06

4 Answers4

6

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 );
});
Navid
  • 894
  • 7
  • 14
  • This solution worked. From my ignorance I didn't realize that it would update the database still, thank you for pointing that out! – Sam5487 Apr 22 '16 at 00:42
0

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.\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);
                    }
                 }
      });
Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45
0

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

Afshan Shujat
  • 541
  • 4
  • 9
0

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