skip to Main Content

I want to send a ajax post request to the page when clicked.My code

$(document).on('click', '#datadel', function(num) {
     $.ajax({
        url:'https://localhost/ajax/ajax_img.php?act=datadel',
        type: 'POST',
        data: {'num':num},
        success: function(infa){
            $('#img-loag-scrin').html(infa);
        }
    }); 
    });

html code

<span id="datadel" class="sf_button_red" value="50">O`chirish</span>

then the value in the span should be sent as a post. what’s wrong with the code I wrote

2

Answers


  1. The span element doesn’t have a value attribute, you could prefix it with data- and get the value with attr or data method.

    Example:

    $(document).on('click', '#datadel', function () {
        $.ajax({
            url: 'https://localhost/ajax/ajax_img.php?act=datadel',
            type: 'POST',
            data: { 'num': $(this).data("value") },
            // data: { 'num': $(this).attr("data-value") }, // alternate method to get the data attribute.
            success: function (infa) {
                $('#img-loag-scrin').html(infa);
            }
        });
    });
    

    HTML:

    <span id="datadel" class="sf_button_reddata" data-value="50">O`chirish</span>
    

    Demo:

    $(document).on('click', '#datadel', function() {
        console.log($(this).data("value"));
        //Ajax request
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="datadel" class="sf_button_reddata" data-value="50">O`chirish</span>
    Login or Signup to reply.
  2. The span tag doesn’t have a value attribute. You can replace the value attribute with any data attribute, like

    <span id="datadel" class="sf_button_red" data-value="50">O`chirish</span>
    

    and the value can be retrieved using the code

    $('datadel').data('value');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search