0

hi guys i have an ecommerce and im using ajax for not loading the page when add to cart is clicked but its not working, when its not logged in products are not adding in to cart but the user is not getting redirect but when its loggedin the add to cart is working well. my data.php, the url in ajax:

<?php
session_start();
require('dbcon.php');
if( isset($_SESSION['nome']) && !empty($_SESSION['nome']) )
{
    //   if(isset($_POST['prodotti-log'])){
         ?>
             <?php
                $pid=$_POST['hidden_id'];
                $hnome=$_POST['hnome'];
                $prezzo=$_POST['hprezzo'];
                $cid=$_SESSION['cid'];
                $pqty=$_POST['qty'];
                $_SESSION['PID'] = $pid;

                $sel="SELECT * FROM cart WHERE pid='$pid' AND cid='$cid'";
                $rs=$conn->query($sel);
                if ($rs->num_rows>0) {
                  while ($row=$rs->fetch_assoc()) {
                    $fqty=$row['qty']+$pqty;
                    $cart_id=$row['id'];
                    $upd="UPDATE cart SET  qty='$fqty' WHERE id='$cart_id'";
                    $conn->query($upd);
                  }
                }
                else {
                
                  $ins = "INSERT INTO cart SET cid='$cid', qty='$pqty', pid='$pid', prezzo='$prezzo',pnome='$hnome'";
                  $conn->query($ins);
                  
                }


               


             
          
        //   } 
          
          // User is logged in, show logout menu here
          
          ?>
            <?php
}
else
{
  // User is not logged in, show login menu here

    // if(isset($_POST['prodotti-log'])) 
    // {
      header('Location: login.php');
    // }
  } ?>

what ajax is doing

<script>
$(document).ready(function() {
    // Bind the forms submit event
    $('.form-prodotti').on('submit', function (event) {
        event.preventDefault();

        // Here we can use $(this) to reference the correct form
        $.ajax({
            method: "POST",
            url: "data.php",
            data: $(this).serialize(),
            success: function (response) {
                // alert("success");
            }
        });
    });
});
</script>

my products form


if(isset($_GET['id']) && $_GET['id']!=''){
$cat_id=mysqli_real_escape_string($conn,$_GET['id']);
if ($cat_id>0) {
    $get_product=get_product($conn,'',$cat_id);
}

else {
    ?>
<script>
    window.location.href = 'index.php';
</script>
<?php
}
}else {
    ?>
    <script>
    window.location.href='index.php';
    </script>
    <?php
}
<?php
             if(count($get_product)>0){
            
            
            foreach($get_product as $list){
                ?>
<!-- alimentari------------------------------ -->
<!-- <div class="item"> -->
<!-- <p class="time">Miglior Prezzo!</p>
    <div class="img-box">
        <img src="images/carrots.jpg" alt="">
    </div>
    <p class="detail">carote buone da mangiare
        </p>
        <a href="#" class="price">Prezzo-€ 1.99(1kg)</a>
        <div class="cart">
            <a href="#">Aggiungi al carrello</a>
        </div>
    </div> -->

    <form action="" method="POST" class="form-prodotti">

    <a href="dettagli_prodotti.php?id=<?php echo $list['id']?>" style="text-decoration:none;">
        <div class="item">
            <div class="slim">
                <img src="<?php echo $list['image'] ?>" alt="">
            </div>
            <div class="slt">

                <p id="p1">
                    <?php echo $list['nome'] ?>
                </p>
                <!-- <p>sapevi che le carote...</p> -->
                <p id="p2">€
                    <?php echo $list['prezzo'] ?>
                    <?php
                   if ($list['type'] == "kg") {
                       ?>
                    (1 <?php echo $list['type'] ?>)
                    <?php
                   }
                   elseif ($list['type'] == "pz") {?>
                      <span>al</span>
                       <?php
                       echo $list['type']; 
                    }
                       
                
                else {?>
<!-- all' -->
<?php
                    echo $list['type'];
                    
                }
                
                ?>
                </p>
            </div>
            <div class="scegli-qty">
                <p>scegli la quantità:</p>

                <div>
                    <?php
                   if ($list['type'] == "kg") {
                       ?>
                    <input type="number" value="1.0" name="qty" step="0.1" max="99999" min="0.1"> <span>kg</span>
                    <?php
                   }
                   elseif ($list['type'] == "pz") {
                       ?>
                    <input type="number" value="1" name="qty" max="99999" min="1"> <span>pz</span>
                    <?php
                }
                
                else {
                    ?>
                    <input type="number" value="1" name="qty" max="99999" min="1"> <span>etto</span>
                    <?php
                }
                
                ?>

                </div>
            </div>
               </a>
            <!-- <input type="number" value="1" name="qty" step="0.1"> -->
            <input type="hidden" name="hidden_id" value="<?php echo $list['id'] ?>">
            <input type="hidden" name="hnome" value="<?php echo $list['nome'] ?>">
            <input type="hidden" name="hprezzo" value="<?php echo $list['prezzo'] ?>">
            <input type="hidden" name="himage" value="<?php echo $list['image'] ?>">
            <div class="cart">
                <!-- <a href="#">Aggiungi al carrello</a> -->
                <input type="submit" name="prodotti-log" value="AGGIUNGI AL CARRELLO">

            </div>


        </div>
        </form>
    <?php
            
        }
    
        ?>

i im also using ridirections in my header:

if( isset($_SESSION['nome']) && !empty($_SESSION['nome']) )
{
      ?>
            <li class='when-loggedin'><a href="#">ciao
                <?php  echo $_SESSION['nome']; ?>!</a>
            </li>
            <li><a href="logout.php">Esci dal account</a></li>

            <li><a href="imieiordini.php">I miei ordini</a></li>
            <?php
      if(isset($_POST['prodotti-log'])){
         ?>
             <?php
                $pid=$_POST['hidden_id'];
                $hnome=$_POST['hnome'];
                $prezzo=$_POST['hprezzo'];
                $cid=$_SESSION['cid'];
                $pqty=$_POST['qty'];
                $_SESSION['PID'] = $pid;

                $sel="SELECT * FROM cart WHERE pid='$pid' AND cid='$cid'";
                $rs=$conn->query($sel);
                if ($rs->num_rows>0) {
                  while ($row=$rs->fetch_assoc()) {
                    $fqty=$row['qty']+$pqty;
                    $cart_id=$row['id'];
                    $upd="UPDATE cart SET  qty='$fqty' WHERE id='$cart_id'";
                    $conn->query($upd);
                  }
                }
                else {
                
                  $ins = "INSERT INTO cart SET cid='$cid', qty='$pqty', pid='$pid', prezzo='$prezzo',pnome='$hnome'";
                  $conn->query($ins);
                  
                }


               


             
          
          } 
          
          // User is logged in, show logout menu here
          
          ?>
            <?php
}
else
{
  // User is not logged in, show login menu here
  ?>
            <li><a href="signup.php">Registrati Subito</a></li>
            <li><a href="login.php">Accedi</a></li>
            <?php
    // if(isset($_POST['prodotti-log'])) 
    // {
    //   header('Location: login.php');
    // }
  }
  ?>

  • what exactly is the problem? What does your ajax load? – vanowm Aug 12 '21 at 15:09
  • 2
    The whole point of using AJAX is to enable you to _stay on the same page_ without any need for reloads, postbacks or redirects. So if the browser sees a redirect header in response to an AJAX request, it ignores it - in this context this is perfectly logical, as I've just described. Your code should simply respond with an error message and/or a 401 error if it receives an AJAX request which requires authentication. – ADyson Aug 12 '21 at 15:09
  • add to cart, if you want i can post my index.html but i think it will be very long. – Muhammad Owais Saeed Aug 12 '21 at 15:10
  • @adyson, ajax can follow the redirect too... – vanowm Aug 12 '21 at 15:11
  • You provided code not relevant to what you are describing here....The ajax expects a response, what response does it get? Start there, not in php. – vanowm Aug 12 '21 at 15:12
  • i was thinking to create 2 add to cart button, 1 to display when user is loggedin, and 1 when he is not, but im fecthing data from database and i think it will overload, what you all think about it? – Muhammad Owais Saeed Aug 12 '21 at 15:13
  • – Muhammad Owais Saeed Aug 12 '21 at 15:15
  • @vanowm `ajax can follow the redirect`... Can you provide a reference for that assertion? I think you are incorrect. It would only redirect if the programmer explicitly puts extra Javascript code into the AJAX call's response callback which then does a client-side redirect (e.g. window.location command). But then, redirecting after an AJAX call would be _completely defeating the point of using AJAX_. `You provided code not relevan` ...nope, that's not true either. There's more than enough info to diagnose the problem, which I've already done in my first comment. – ADyson Aug 12 '21 at 15:15
  • @MuhammadOwaisSaeed if you have extra code to share please paste it into your question, not the comments. As you can see, it's not very easy to read it in the comments. You have an "edit" button at the end of your question just below the little blue tags - please use that, thanks. – ADyson Aug 12 '21 at 15:16
  • @ADyson by follow redirect I meant follow redirect headers to retrieve the data. So in the OP example it should get data from login.php if user is not logged in. – vanowm Aug 12 '21 at 15:21
  • @MuhammadOwaisSaeed P.S. **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Aug 12 '21 at 15:21
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Aug 12 '21 at 15:21
  • @vanowm `by follow redirect I meant follow redirect headers to retrieve the data. So in the OP example it should get data from login.php if user is not logged in`...no, AJAX doesn't do that. It doesn't follow a redirect header. It will not change the page to login.php, despite the `location` header being set. And it would not provide the content of login.php directly in the AJAX response either, that's not a redirect and it's not what the `header: location` command achieves. From that remark I think unfortunately you do not understand the mechanics of AJAX or redirection properly at all. – ADyson Aug 12 '21 at 15:23
  • i have added all the ifo you need i have, so my suggestion of doing 2 buttons is the only option? – Muhammad Owais Saeed Aug 12 '21 at 15:33
  • @ADyson, I don't know what you are talking about. XHR [follows](https://www.w3.org/TR/XMLHttpRequest1/#infrastructure-for-the-send-method) the redirects `if the response has an HTTP status code of 301, 302, 303, or 307 If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.` – vanowm Aug 12 '21 at 15:34
  • @vanowm ok sorry I was wrong about the last part, you're correct that if the status code is 302 it would go and request the redirected URL before returning the AJAX. But all it would do is return the contents of login.php inside the AJAX response ... and that's not what the OP wants, they want the whole page to be redirected to login.php, and that isn't going to happen - which was my original point. – ADyson Aug 12 '21 at 15:38
  • @MuhammadOwaisSaeed `i was thinking to create 2 add to cart button, 1 to display when user is loggedin, and 1 when he is not`...this would make no difference to anything. It's also impractical because the session could easily time out while the user is on the page and in that situation you can't easily just display another button while the page is already loaded. The important thing is how the server responds to the click of that button, if they are logged in or not. Go back to my first comment. – ADyson Aug 12 '21 at 15:41
  • @ADyson ok, but how can i adjust the problem? – Muhammad Owais Saeed Aug 12 '21 at 15:46
  • which condition i have to put for the error? – Muhammad Owais Saeed Aug 12 '21 at 15:47
  • @MuhammadOwaisSaeed Personally I'd suggest setting a HTTP 401 response via PHP (see https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code for details). AJAX can then detect that (via its error callback usually) and then maybe you can do a client-side redirect to your login page via the window.location command. You also may want to consider the user experience if the user's session expires while they have a half-completed cart...will it destroy their session and their entire cart, or do you have a way of restoring it in the database for them when they log back in? – ADyson Aug 12 '21 at 15:53
  • no no i restore it in the database – Muhammad Owais Saeed Aug 12 '21 at 16:16
  • I think you don't need Ajax here, the normal form submit behavior would be enough. – Mohammed Khurram Aug 17 '21 at 11:45

0 Answers0