1

so I am at a bit of a bind here. So I have 2 jQuery scripts that handle a simple database row update (per the user ID, session), this lets the user send a "Gift" that adds value to the users database row column "bonus".

I got this working practically perfect, but the problem is: It will only get the first ID of the results when gifting, not any other user ID. I suspect this is a fault in the looping logic.

RequestBin tells me I have my correct ID for myself, and the user ID is stuck with the first iterated userid (we cant send to any other user ID). We need to be able to gift any result (user ID).

We use a dialog to trigger the AJAX call with Yes / No. Yes firing the AJAX event, no closing model.

The AJAX JS - Sends value to database

function ConfirmDialog(message) {
    $('<div></div>').appendTo('body')
        .html('<div><h6>' + message + '</h6></div>')
        .dialog({
            modal: true,
            title: 'Gift this user new Gift?',
            zIndex: 10000,
            autoOpen: true,
            width: '600',
            height: '200',
            resizable: false,
            buttons: {
                Yes: function () {
                    $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
                    $(this).dialog("close");
                    var sender = $('input[name=sender]').val();
                    var receiver = $('input[name=receiver]').val();
                    $.ajax({
                        url: 'https://xxxxx.m.pipedream.net',
                        type: 'POST',
                        data: {
                            sender: sender,
                            receiver: receiver
                        },
                        beforeSend: function () {
                            $('#gift-bonus-status').text('Sending...').delay(100).fadeIn().delay(100).fadeOut();

                        },
                        success: function (response) {
                            $('#gift-bonus-status').text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
                        }
                    });
                },
                No: function () {
                    $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');

                    $(this).dialog("close");
                }
            },
            close: function (event, ui) {
                $(this).remove();
            }
        });
};
function fetchTopTransfers() {
    $(function () {});
    $.ajax({
        url: '/ajax/ajax_user_list.php',
        method: 'GET',
        dataType: 'JSON',
        success: function (data) {
            var html_to_append = '';
            $.each(data, function (i, item) {
                $('input[name=receiver]').val(item.user_id);
                html_to_append +=
                    '<div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' + 
                    item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' + 
                    item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' + 
                    formatBytesProduct(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\')" id="gift-bonus-status">Give Gift</a></div></div><div style="padding-bottom:5px">' + 
                    item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' + 
                    item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' + 
                    item.progress + '%</div></div></div><div style="clear:both"></div><input type="hidden" name="sender" value="<?=$account->getId()?>" /><input type="hidden" name="receiver" value="' + 
                    item.user_id + '" />';
            });
            $("#top-transfers").html(html_to_append);
        }
    });
}
fetchTopTransfers();
setInterval(function () {
    fetchTopTransfers()
}, 5000);

AJAX responce:

What is happening here???

Any help is much appreciated

10
  • where exactly is it going wrong? Is it sending the wrong ID to the server, or receiving the wrong ID back from the server? Or something else? You're talking about a wrong ID but there are several places in your code where IDs are used. Please be more specific. Commented Jan 24, 2021 at 21:04
  • There are listed 4 users. Each has a user ID unique. We can only at all times retrieve the First user ID, it ignores the 3 other users in the GET/JSON results Commented Jan 24, 2021 at 21:07
  • Ok. How many input boxes with name=receiver exist in your page? Because $('input[name=receiver]').val() will set the value of all of them at once every time you run that command. is that what is happening? It sets all your inputs to the same ID? You still are being a bit vague about the precise behaviour you're seeing. Commented Jan 24, 2021 at 21:12
  • That is exactly what is happening. We have 2 input boxes (nowhere else), in the first JS function that holds these values, and updates the receiver hidden input with what is received back from AJAX data. Is this a issue with $.each() ? Commented Jan 24, 2021 at 21:14
  • 1
    Sorry I'm not sure what you're saying. All I said was to remove one line of code. This does not remove the ability of the script to set the user ID - like I said, the line <input type="hidden" name="receiver" value="' + item.user_id + '" /> already sets the correct value. Commented Jan 24, 2021 at 22:36

1 Answer 1

2

As there many inputs with name receiver that's why you are not able to pass correct values. So, inside your ConfirmDialog function pass this as well it will refer to current element which is clicked. Then , inside your function to get required values you can use $(this).closest(".outer").find(..)...

Demo Code :

//just for demo..
var data = [{
  "user_id": 1,
  "product_id": 12,
  "username": "acc",
  "name": "swi",
  "progress": "20",
  "speed": 15
}, {
  "user_id": 2,
  "product_id": 12,
  "username": "acc",
  "name": "swi22",
  "progress": "10",
  "speed": 12
}]
var html_to_append = "";
$.each(data, function(i, item) {
  //give outer div.. also pass `this` inside your function
  html_to_append +=
    '<div class="outer"><div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
    item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
    item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
    (item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\',this)" >Give Gift</a></div></div><div style="padding-bottom:5px">' +
    item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
    item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
    item.progress + '%</div></div><div style="clear:both"></div><input type="hidden" name="sender" value="23" /><input type="text" name="receiver" value="' +
    item.user_id + '" /></div>';
});
$("#top-transfers").html(html_to_append);
//add el it refer to `this`
function ConfirmDialog(message, el) {
  $('<div></div>').appendTo('body')
    .html('<div><h6>' + message + '</h6></div>')
    .dialog({
      modal: true,
      title: 'Gift this user new Gift?',
      zIndex: 10000,
      autoOpen: true,
      width: '600',
      height: '200',
      resizable: false,
      buttons: {
        Yes: function() {
          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
          $(this).dialog("close");
          //get closest div(outer) then find required inputs values
          var sender = $(el).closest(".outer").find('input[name=sender]').val();
          var receiver = $(el).closest(".outer").find('input[name=receiver]').val();
          console.log("Reciver --" + receiver + " Sender ---" + sender)
          $.ajax({
            url: 'https://xxxxx.m.pipedream.net',
            type: 'POST',
            data: {
              sender: sender,
              receiver: receiver
            },
            beforeSend: function() {
 //use el here as well.. 
 $(el).text('Sending...').delay(100).fadeIn().delay(100).fadeOut();

            },
            success: function(response) {
            //use el here as well
              $(el).text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
            }
          });
        },
        No: function() {
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');

          $(this).dialog("close");
        }
      },
      close: function(event, ui) {
        $(this).remove();
      }
    });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />

<div id="top-transfers">
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.