0

I am trying to implement, an ajax function that will take the id's of products on load and checks against the db to see if that user has it in their wishlist, then use that information to change the color of wishlist icon.This happens on load of the page.

Currently the function runs but it only looks at the first item, and functions as intended to but not on the remaining products.

Any help on this would be really appreciated, many thanks

The javascript

<script type="text/javascript">
window.onload = function(){

       var link_data = $(".add-wishlist").data('data');   
       $.ajax({
          type: "POST",
          url: '../source/wishlist_control.php',
          data: ({fav_check: link_data}),
          success: function(data) {

               if(data.replace(/\s+/, "")  == 'YES')
               {
                  $('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"#EB686C"})

               }
               else if (data.replace(/\s+/, "")  == 'NO'){
                   $('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"gray"})

               }
               else {

               }
          } 
       });

    }; 

</script>

The icon with the id that is being printed the page

<a class="add-wishlist" href='javascript:;' data-data='<?php echo protect($usri['id']); ?>'>
<i class='fa fa-heart whishstate'></i>
</a>

The php file code

if(isset($_POST['fav_check'])) {  
    $addmemberid = $_SESSION['user_id'];
    $addproductid = $_POST['fav_check'];
    $result = mysql_query("SELECT count(product_id) cnt FROM users_wishlist WHERE user_id = '$addmemberid' AND product_id = '$addproductid'") or die(mysql_error());
    $countid = mysql_fetch_assoc($result);
    if($countid['cnt'] == 1){
        echo 'YES';
    } else {
         echo 'NO';
    }
}
  • 2
    Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Sep 29 '16 at 10:59
  • There we go again @RiggsFolly – Phiter Sep 29 '16 at 11:11
  • 1
    Seriously those outdated tutorials should be banished from the internet if the authors don't update them. Everyone that starts learning PHP ends up coding with `mysql_*` because of those tutorials. – Phiter Sep 29 '16 at 11:13
  • @PhiterFernandes We need to form a group and search them all out, post comments to the effect that they are all out of date – RiggsFolly Sep 29 '16 at 11:46
  • That is a good idea, but there are so many of them, in the most different languages. I'm a native portuguese speaker and most tutorials I have seen in this language are outdated. – Phiter Sep 29 '16 at 12:12
  • @RiggsFolly or keep working on PHP documentation until that becomes the definitive resource and to google result for tutorials. – Rafael Emshoff Sep 29 '16 at 12:14
  • The php documentation (the one at php.net) is very useful but it's too technical for beginners. Codeacademy is way easier to understand for who has no idea about how to write code. – Phiter Sep 29 '16 at 12:20
  • 1
    @PhiterFernandes yup. when I said Group I did mean a BIG Group – RiggsFolly Sep 29 '16 at 12:24
  • We could arrange that. – Phiter Sep 29 '16 at 13:01

2 Answers2

0

The jquery selector will only select the data first element matched. to do that to all elements you have to loop over them using jQuery each function:

$(".add-wishlist").each(function() {
   var link_data = $(this).data('data');   
   $.ajax({
      type: "POST",
      url: '../source/wishlist_control.php',
      data: ({fav_check: link_data}),
      success: function(data) {

           if(data.replace(/\s+/, "")  == 'YES')
           {
              $('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"#EB686C"})

           }
           else if (data.replace(/\s+/, "")  == 'NO'){
               $('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"gray"})

           }
           else {

           }
      } 
});
Yacine al
  • 163
  • 2
  • 8
0

Instead of putting AJAX call in a loop, try creating an array of wishlist IDs and POST that to server in a single AJAX call. Then in server you can fetch the respective data and return that as array to the AJAX success function. This will save multiple AJAX request and increase the performance.
So the code will look something like this:

var link_data = [];
$(".add-wishlist").each(function() {
  link_data.push($(this).data('data'));
});
$.ajax({
  type: "POST",
  url: '../source/wishlist_control.php',
  data: ({fav_check: link_data}),
......
......
souravb
  • 121
  • 8
  • How do i go about doing that? i am still trying to learn php and ajax, so any help on this info would be really really appreciated, – Databoy414 Sep 29 '16 at 11:10
  • the ajax call works :D , On the php side how do i process this, i get the error "Notice: Array to string conversion in line 29" and again thank you soo much for helping me out :) – Databoy414 Sep 29 '16 at 11:39
  • On php side, you can loop through the array and query the database for each ID. Then you store the query result in an array and return it back on ajax success. – souravb Sep 29 '16 at 13:47
  • hey, this the code i wrote to handle the request, but the success is expecting just YES, but now all i am returning is the id of products that are actually success. – Databoy414 Sep 29 '16 at 14:15
  • this is the code `if(isset($_POST['fav_check'])) { $addmemberid = $_SESSION['user_id']; $addproductid = $_POST['fav_check']; $search = "SELECT * FROM users_wishlist WHERE user_id = '$addmemberid' AND product_id IN (" . implode(',', $addproductid) . ")"; #echo $search; $result = mysql_query($search) or die(mysql_error()); $rows = []; while ($row = mysql_fetch_assoc($result)) { array_push($rows, $row); } #var_dump($rows); foreach($rows as $item) { #echo "{"; echo $item['product_id']; echo ","; } #echo "}"; }` – Databoy414 Sep 29 '16 at 14:16
  • return array of objects to ajax success like this: `[{"id": "1", "response": "yes"}, {"id": "2", "response": "no"}]`. Then on success request you can loop through. – souravb Sep 30 '16 at 05:40