It was necessary to obtain data from the data-user_id attribute

$('.submit_button').click(function () { $.ajax( { url:'/../title/comment', type:'post', data: { 'comment_text': $('#comment_area').val(), 'title_id' : $(this).data('title_id'), }, success:function (data) { if (data != "u're guest") if (data !='update') $('#comment_area').prepend(data); else { alert($('.submit_button').data('user_id')); ) } else alert('Чтобы оставлять комментарии войдите в профиль'); //Checking if user is logged in } } ) 

});

Displays undefined, while the values ​​from the title_id attribute can be obtained

    3 answers 3

    Before the request, save the current element ( $(this) ) to a variable, and already in the request to the place of $(this) use that variable, and you get user_id because you do not use $(this) and immediately select an element with a class ( $('.submit_button').data('user_id') ).

     $('.submit_button').click(function() { var this_button = $(this); $.ajax( { url: '/../title/comment', type: 'post', data: { 'comment_text': $('#comment_area').val(), 'title_id': this_button.data('title_id'), }, beforeSend: function(){ console.log(this_button.data('title_id')); }, success: function(data) { if (data != "u're guest") if (data != 'update') $('#comment_area').prepend(data); else { alert($('.submit_button').data('user_id')); } else alert('Чтобы оставлять комментарии войдите в профиль'); } } ) }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="submit_button" data-title_id="title_idd" data-user_id="xxx">click</div> 

      You can use getAttribute :

       let element = document.getElementByClassName('submit_button')[0]; //получаем элемент по классу let result = element.getAttribute('data-user_id'); 

         $('.submit_button').click(function(){ alert($(this).data('title_id')); }) 
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="submit_button" data-title_id="title_idd" data-user_id="xxx">click</button> 

        var user_id = $ (this) .data ('user_id');

        Something like this. Sorry, my data error is not taken into account ... This code will work ...

        • Read here this article https://habrahabr.ru/post/139210/ , and documentation https://api.jquery.com/data/ . And the advice if you probably do not know that the answer is correct, do not give an answer, so as not to mislead the person who asked the question. - Raz Galstyan
        • First, check the code, and then criticize ... You probably still use version 1.3 for this and it does not work ... - Web Desg
        • Checked and without ajax request the answer is undefined . - Raz Galstyan
        • Check out ...... - Web Desg
        • Well, it will work this way, and you wrote $(this).data('data-user_id'); . This and $(this).data('user_id'); Different things. - Raz Galstyan