简体   繁体   中英

jQuery - Getting Correct UserID - AJAX

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM