0

To start off my code (well the main part) is actually working as it should, there is just a small issue I can't seem to get past, I'm using ajax to interact with a .PHP file.

Main file:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    include($_SERVER['DOCUMENT_ROOT'] . "/includes/inc-db-connection.php");
    include($_SERVER['DOCUMENT_ROOT'] . "/includes/inc-functions.php");
    
    if (isset($_POST['theSite_search_query'])) {
        
        echo "<hr />";
        
        if (empty($_POST['theSite_search_query'])) {
            
            stdErr("You never entered a <strong>product</strong>!");
            
        } else {    
        
            echo "<p>Results for ... <span class='text-success'><strong>{$_POST['theSite_search_query']}</strong></span></p>";
            echo "<hr />";

            $html = gzdecode(file_get_contents("https://www.theSite.co.uk/s?k=" . urlencode($_POST['theSite_search_query']) . "&crid=1OIBJTPCDBWDZ&sprefix=" . urlencode($_POST['theSite_search_query']) . "%2Caps%2C176&ref=nb_sb_noss_1", false, $context));  

            $theSiteScraper = parsetheSiteSearchPage($html);    

            if (!empty($html)) { ?>         
                
                <div class="table-responsive">
                <table class="table table-striped row-border" id="tableProducts" width="100%" cellspacing="0">    
                  <thead>
                    <tr>
                      <th><i class="fas fa-image"></i></th>
                      <th>Link / Description / price / Actions</th>
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                      <th><i class="fas fa-image"></i></th>
                      <th>Link / Description / price / Actions</th>
                    </tr>
                  </tfoot>
                  <tbody>     
                        <?php foreach ($theSiteScraper as $node) { ?>
                        
                            <tr>
                                <td><img src="<?= $node["productImage"]; ?>"></td>  
                                
                                <?php if (getIsProductInDBCount(md5("https://www.theSite.co.uk" . $node["productLink"])) > 0) { ?>
                                
                                    <td>
                                        <strong>URL:</strong> <a href="https://www.theSite.co.uk<?= $node["productLink"]; ?>" class="text-decoration-none" target="_blank">https://www.theSite.co.uk<?= $node["productLink"]; ?></a>
                                        <br />
                                        <strong>Product Name:</strong> <small><?= $node["productDescription"]; ?></small>
                                        <br />
                                        <strong>Price:</strong> <span class="text-success"><?= $node["productPrice"]; ?></span>
                                        <br />
                                        <strong>Status:</strong> <i class="fas fa-check" style="color:green"></i> in your shop already!
                                    </td>                               
                                    
                                <?php } else { ?>
                                
                                    <td>
                                        <strong>URL:</strong> <a href="https://www.theSite.co.uk<?= $node["productLink"]; ?>" id="productLink" class="text-decoration-none" target="_blank">https://www.theSite.co.uk<?= $node["productLink"]; ?></a>
                                        <br />
                                        <strong>Product Name:</strong><small> <?= $node["productDescription"]; ?></small>
                                        <br />
                                        <strong>Price:</strong> <span class="text-success"><?= $node["productPrice"]; ?></span>
                                        <br />
                                        <strong>Status:</strong> <a href="#" data-bs-toggle="tooltip" data-placement="bottom" id="importProduct" value="https://www.theSite.co.uk<?= $node["productLink"]; ?>|<?= $node["productImage"]; ?>|<?= $node["productDescription"]; ?>|<?= $node["productPrice"]; ?>|<?= $_POST['theSite_search_catid']; ?>" title="Add to your shop"><i class="fas fa-file-import"></i></a><div id="status"></div>
                                    </td>                           
                            
                                <?php } ?>                          
                            </tr>   
                            
                        <?php } ?>  
                  </tbody>    
                </table>
                </div>   
                
                <script type="text/javascript">  
                $(document).ready(function(){     
                   $("#importProduct").on('click', function(e) {
                      e.preventDefault();  
                      var productDetails = $(this).attr('value');
                      alert(productDetails);
                      $.ajax({  
                         type:"POST",  
                         url: "https://www.url.com/ajax-import.php",  
                         data: {
                                "theSite_data":productDetails                               
                                },
                         success: function(results) {  
                            $('#status').html(results);
                         },
                         error: function(data) {
                            alert("Uh oh! AJAX error!");
                         }  
                      });  
                   }); 
                });        
                </script> 
                
            <?php 
          
            } 
            
        }
        
    }
    
}

?>

The .PHP file posted to by the above file:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    include($_SERVER['DOCUMENT_ROOT'] . "/includes/inc-db-connection.php");
    include($_SERVER['DOCUMENT_ROOT'] . "/includes/inc-functions.php");
    
    if (isset($_POST['data'])) {
        
        try {
            
            $dataSplit = explode('|', $_POST['data']);
            $i = DB::getInstance()->insert(
                'products',
            [
                'product_category_id' => $dataSplit[4],     
                'product_name' => $dataSplit[2],        
                'product_description' => "...", 
                'product_original_image_url' => $dataSplit[1],      
                'product_original_url' => $dataSplit[0],    
                'product_price' => str_replace("£", "", $dataSplit[3]), 
                'product_unique_md5' => md5($dataSplit[0]),         
                'product_date' => date('Y-m-d H:i:s')
            ]); 
            
            stdMsg("Your new <strong>product</strong> has been imported <strong>successfully</strong>.");

        } catch (Exception $e) {
            stdErr($e->getMessage());
        }
        
    }
    
}

?>

The problem with the code is, this part id="importProduct" only fires the ajax code once, instead of going down the list of items and clicking until you are finished, it only allows you to click on the first link in the <?php foreach ($theSiteScraper as $node) { ?> loop.

I'm sure it is to do with the fact each of these ID's id="importProduct" should be unique? like:

id="importProduct1"
id="importProduct2"
etc

I place the values I need to pass through in a value="" like this value="https://www.theSite.co.uk<?= $node["productLink"]; ?>|<?= $node["productImage"]; ?>|<?= $node["productDescription"]; ?>|<?= $node["productPrice"]; ?>|<?= $_POST['theSite_search_catid']; ?>"

I'm not sure if I'm on the right track with what i think is wrong, any fresh eyes on the issue would be appreciated.

logosapp
  • 21
  • 5
  • 1
    *"I'm sure it is to do with the fact each of these ID's should be unique?"* - That's exactly the issue. An ID is a unique identifier. So once the browser finds the single unique element it's looking for, there's no reason for it to keep looking. You might try using a class instead of an ID. – David Apr 15 '22 at 17:16
  • Thank you, David :) would each class need to be unique? I will amend the code and try thanks again. – logosapp Apr 15 '22 at 17:32
  • Classes do not need to be unique, no. If you assign a class to each element you want to be clickable in this context, and then use a class selector to assign a click event handler in jQuery, it will assign it to every matching element. – David Apr 15 '22 at 17:33

0 Answers0