-1

So our project is to make an ordering website, we had everything down design-wise. Now that the designing is done, we're now focused to the function of the website. I've done a different approach where i'm able to insert an item into the database but the php page reloads everytime I add an item. I want to make my ordering page be able to add an item and not reload, i've searched on how to do it and it says i have to use a javascript or ajax, this is what i've tried so far as i don't actually know javascript

this is my ordering php page

function onSubmit() {
  $.ajax({
    url: 'inserttocart.php',
    method: 'post',
    data: $("#orderid").serialize(),
    success: function(response) {
      alert(response);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("Status: " + textStatus);
      alert("Error: " + errorThrown);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="orderid">
  <p><br>Your choice of 1 marinade: </p>
  <input class="chkb1" type="checkbox" name="choice1" value="Bulgogi">&nbsp Bulgogi<br>
  <input class="chkb1" type="checkbox" name="choice1" value="Galbi">&nbsp Galbi<br>
  <input class="chkb1" type="checkbox" name="choice1" value="Gochujang">&nbsp Gochujang<br>
  <input class="chkb1" type="checkbox" name="choice1" value="JRAMS">&nbsp JRAMS Special

  <button class="cart-button" type="button" onclick="onSubmit()" id="addtocartbtn" name="beefbtn">
    <span class="add-to-cart">Add to Cart</span>  
    <span class="added">Added</span>
    <i class="fas fa-shopping-cart"></i>
    <i class="fas fa-box"></i>
  </button>
</form>

This is my inserttocart.php

$connect = mysqli_connect("localhost", "root", "", "pigmedb");
if ($connect == false) {
  die("ERROR: Could not connect. ".mysqli_connect_error());
}
if (isset($_POST['choice1']) && (isset($_POST['beefbtn']))) {
  $marinade = ($_POST['choice1']);

  if ($connect == false) {
    die("ERROR: Could not connect. ".mysqli_connect_error());
  }
  if ($marinade == "Bulgogi") {
    $sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Bulgogi Marinated)'";
  }
  elseif($marinade == "Galbi") {
    $sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Galbi Marinated)'";
  }
  elseif($marinade == "Gochujang") {
    $sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Gochujang Marinated)'";
  }
  elseif($marinade == "JRAMS") {
    $sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (JRAMS Special Marinated)'";
  }


  $result = mysqli_query($connect, $sqlresult);

  if (mysqli_num_rows($result) > 0) {
    // row exists
    echo "Item Already Added";


    mysqli_close($connect);

  } else {
    if ($marinade == "Bulgogi") {
      $sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Bulgogi Marinated)', '1', '399')";
    }
    elseif($marinade == "Galbi") {
      $sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Galbi Marinated)', '1', '399')";
    }
    elseif($marinade == "Gochujang") {
      $sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Gochujang Marinated)', '1', '399')";
    }
    elseif($marinade == "JRAMS") {
      $sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (JRAMS Special Marinated)', '1', '399')";
    }
    else {
      echo "Please select one of the marinade of the Beef Set.";

    }

    if (mysqli_query($connect, $sql)) {
      echo "Added to Cart";

    } else {
      echo "ERROR: Could not able to execute $sql. ".mysqli_error($connect);

    }
    mysqli_close($connect);

  }

}

My goal is to prevent the first page from reloading as this is a cart, but at the same time, its able to insert an item into the mysql database. pls help thank you

  • So what is the issue? Your ajax seems to work (I added jQuery library - make sure you load that) and is not reloading the page – mplungjan Nov 24 '20 at 07:09
  • The 1st step to debug is to check the server response in browser's Developer Console. Is there any JS error? or is the server response normal? I recommended you to format your PHP response using JSON format, instead of just echoing texts without specifying the Content Type. Btw, your HTML codes contain minor errors, e.g. ` ` instead of `&nbsp` – Raptor Nov 24 '20 at 07:09
  • You should wrap in a label to allow clicking the text too `` ` – mplungjan Nov 24 '20 at 07:11
  • Why do you check `if ($connect == false)` twice? – Barmar Nov 24 '20 at 07:15
  • 1
    Please narrow your problem down. If your only problem is how to prevent submitting the form is then you could have easily googled that. [This might help you](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission). – Definitely not Rafal Nov 24 '20 at 07:16
  • is the javascript snippet needs to be before the form or after? or it doesnt really matter where? i dont know javascript so please bare with me – John Henry Suarnaba Nov 24 '20 at 07:17
  • @JohnHenrySuarnaba idealy the JavaScript should be placed near the bottom of the HTML, before the end tag of HTML body `

    `. However, if you wrap the JS with [document ready function](https://learn.jquery.com/using-jquery-core/document-ready/), you can put it before the form, or in the `

    ` section, as long as your customized script is AFTER the jQuery script, as JS loads from top to bottom.

    – Raptor Nov 24 '20 at 07:22
  • i removed the copied `if ($connect == false)` it was a pasting error thanks for that – John Henry Suarnaba Nov 24 '20 at 07:23
  • And you can simplify the PHP codes using `switch` clause. – Raptor Nov 24 '20 at 07:27

1 Answers1

0

Buttons aren't included in the result of .serialize(), since it doesn't know which button was clicked. So $_POST['beefbtn'] won't be set.

You can add it yourself.

data: $("#orderid").serialize() + '&beefbtn=1'

Or you could remove that check from the PHP.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i have tried without the `$_POST['beefbtn']` check, so i thought i needed to include that in the php, it didn't work. i'll try adding the button in the `.serialize()` thanks – John Henry Suarnaba Nov 24 '20 at 07:33
  • update. yo it worked, the page doesnt reload anymore after clicking the button, that was my main problem, thank you so much – John Henry Suarnaba Nov 24 '20 at 07:38