0

I have been trying to insert data into a table in a mysql database. This data was sent with ajax using the POST method. However, when I try to insert it into the database nothing happens.

So here is the javascript function the sends the data to the php file.

 addToCart: function(itemId,userId){
              let request = new XMLHttpRequest();
              request.open("POST", "../E-CommerceCore/addToCart.php?
              itemId="+ itemId + "?userId=" + userId, true);
              request.send();
            },

Here is where it is being used. This is nested in a bigger function so thats where the book[i].Id comes from.

   document.getElementById('add-to-cart').onclick = function(){
    cartFunctions.addToCart(book[i].Id, '1');
   };

So this takes an item id and a user id and stores them in a php variables here.

 class Cart
{
  public function addToCart($item,$user){
    include 'connect.php';
    $query = $bookStore->prepare("INSERT INTO cart SET item_Id=?, user_Id=?");
    $query->execute([$item,$user]);
  }
}

$cartManager = Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];

$cartManager->addToCart("$itemId","$userId");

This php file then runs the addToCart function which should insert it into the table. This is where I run into the problem because not data is inserted to the database when the user clicks the button. I use the connect.php file for another controller that selects from a different table in the same database, if that is an issue, and yes I have checked to make sure that the connection to the database is good. Any insight would be immensely appreciated. Please no jQuery solutions. Thank you for you time and effort.

Matt Comeaux
  • 91
  • 2
  • 8
  • why are you passing the variables $itemId and $userId inside double quotes: $cartManager->addToCart("$itemId","$userId"); ? – JV Lobo Mar 27 '18 at 00:25
  • have you checked in the php the posted variables exist? –  Mar 27 '18 at 00:25
  • You'll need to remove quotes from `addToCart("$itemId","$userId")` – Lece Mar 27 '18 at 00:28
  • `request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true);` you are sending the parameters as GET with the url and you have another mistake since you used 2 **?** . Pleasw follow this link to send your data: https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest – Omar Tanti Mar 27 '18 at 00:33

1 Answers1

1

request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true); You are sending the parameters as GET with the url and you have another mistake since you used another ? to separate the 2 parameters . Please follow this link to send your data: Send POST data using XMLHttpRequest

var http = new XMLHttpRequest();
var url = "path_to_file.php";
var params = "itemId="+ itemId + "&userId=" + userId; //Please note that the 2 params are separated by an **&** not a **?** as in your question
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
    }
}
http.send(params);

Also the quotes here are unnecessary when passing parameters:

$cartManager->addToCart("$itemId","$userId");

If it is possible try to var_dump($_REQUEST) before calling the addToCart method to make sure that parameters have been successfully sent through the javascript request.

Now regarding the sql query you have to update the class and use bindParam and afterwards call the execute. I have updated your php code as follows:

class Cart{
  public function addToCart($item,$user){
        include 'connect.php';
        $query = $bookStore->prepare("INSERT INTO cart SET item_Id=:item_id, user_Id=:user_id");
        $query->bindParam(':item_id', $item);
        $query->bindParam(':user_id', $user);
        $query->execute();
    }
}

$cartManager = new Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];

$cartManager->addToCart($itemId, $userId);

For more reference regarding prepared statements you can have a look at this: http://php.net/manual/en/pdo.prepared-statements.php

Omar Tanti
  • 1,368
  • 1
  • 14
  • 29
  • Okay so I tried that. I can confirm that the data is being sent successfully to the php file. However, the php file still isn't inserting it into the database. I have tried changing the sql to INSERT INTO ... VALUES ... instead of INSTERT INTO ... SET ... That didn't work. I also remove the quote marks from the addToCart function. – Matt Comeaux Mar 27 '18 at 01:04
  • This is being sent when a button is clicked, do I need to change the header information from x-www-form-urlencoded? I have never used setRequestHeader() before. – Matt Comeaux Mar 27 '18 at 01:11
  • Yes keep using `setRequestHeader`. I have updated my code to use bindParam method before executing the sql query, can you try my updated code and let me know if it worked. – Omar Tanti Mar 27 '18 at 04:48
  • Okay well I fixed the main issue, besides the ones you pointed out. It was a variable name conflict in the connect.php file that I didn't include. Sorry about that. I haven't tried the bindParam part, but everything works now. Thank you very much for your time Omar, I learned a lot. – Matt Comeaux Mar 27 '18 at 08:21
  • You're welcome, glad you sorted out the issue, in fact I was going to ask for the code of connect.php if the problem would still have persisted. – Omar Tanti Mar 27 '18 at 08:25