Good time to all. Guys, I sit puzzle how to do that you press the button and it became green and next to the diva flashed (1), you press the second time and the button is already blue, highlighted (0). On the Internet, I found something completely different from what I need or the button changed when you hold the color, when you press it, it returns to the original color, but you need to be fixed.

    2 answers 2

    To learn AJAX, I recommend starting with articles from Kantor’s textbook: 1 article and 2 article

    let result = 0; let myEvent = function() { if (result == 0) { document.getElementById('my-button').style.backgroundColor = 'green'; result++; } else { document.getElementById('my-button').style.backgroundColor = '#47a4ff'; result--; } let xhr = new XMLHttpRequest(); xhr.open('POST', url, false); //url по которому будет выполнятся запрос let body = 'result=' + result; xhr.send(body); if (xhr.status == 200) { document.getElementById('result').innerHTML = result; } else { alert('При отправке данных произошла ошибка'); } } 
     #my-button { background-color: #47a4ff; } 
     <button id="my-button" onclick="myEvent()">Жмакни меня!</button> <div id="result">0</div> 

    • Damn, Sergey, I apologize for my emotionality, but you are just God) I just remember that in some topic you also helped me out. Thank you very much) And by the way, you can do all this on JSON so that you can output data from the DB according to the principle (pressed the button and enrolled the unit in the database, once again pressed and recorded zero) - Karter
    • This is not possible from the client JS file, for this you need to send a request to the server, and the server will already write / rewrite your JSON, for this you need to know what your server is written on - php, nodeJS, asp.net, etc. . etc. - Sergey Glazirin
    • mixed up, not JSON, but AJAX so that you can write one or zero to the database (to the table) when you press it again. - Karter
    • watched examples with voting but probably due to the fact that I am far from the topic of AJAX did not particularly understand what was happening ( - Karter
    • Added sending AJAX request, you only need to substitute your URL and processing on the server. If there are any other questions, it is better to ask a new question. - Sergey Glazirin

    On plain js answered above. Using jquery:

     var flag = 0; $('.bt').click(function() { if (flag == 0) { $('.bt').css('background', 'green'); flag++; } else { $('.bt').css('background', 'blue'); flag--; } $('.res').text(flag); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="bt">Button</button> <div class="res">0</div> 

    • Thanks Artem for such a quick response. - Karter
    • @technoimpex technoimpex not at all) - artem55555p