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.

6
  • 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. Commented Apr 21, 2016 at 3: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? Commented Apr 21, 2016 at 3: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? Commented Apr 21, 2016 at 3:31
  • Nope. Because it sends nothing in the second call. The request is empty on the second call. Commented Apr 21, 2016 at 3:33
  • @NMoeini So the code should be working, I'm just not seeing it? How can I verify that my data is being posted? Commented Apr 21, 2016 at 3:37

4 Answers 4

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 );
});
Sign up to request clarification or add additional context in comments.

1 Comment

This solution worked. From my ignorance I didn't realize that it would update the database still, thank you for pointing that out!
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",

Comments

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

Comments

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

5 Comments

let me know if didnot work
I received a status error: 0. Which doesn't make sense that I'm not connected.
it means your url is not correct..... is this file really exists in your file localhost:8888/checkout.php
its working in my test example if you want i can upload for you
hello sir, if data isnot posting just remove contentType:"application/json "... remove that line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.