When you click on the .btn class, you need to add a test block to the .container with values ​​from the JS object, and then somehow send this data to the database for further processing.

Unfortunately, I do not know where to start. I understood only one thing: I need to send an ajax request to something like this:

$.ajax({ url: "test.php", type: "post", dataType: "json", data: { } 

Object to shove in JSON. But where to push this AJAX code, how to associate with the variable water, what to write in PHP code is no idea.

I would be grateful for any help - links, maybe some other solutions.

 var water = { name: 'water', count: 200 }; $('.btn').on('click', function() { $('.container').append( `<div class='test'>\n<div class='test__name'>${water.name}</div>\n<div class='test__price'>${water.count}</div>\n</div>` ); }); 
 .btn { width: 100px; height: 100px; background-color: red; } .container { background-color: #2a66ad; } .test { color: #000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="btn"> </div> <div class="container"> <div class="test"> <div class="test__name"> </div> <div class="test__price"> </div> </div> </div> 

  • (with values ​​from the array) what kind of array (this data) is what these are - qwabra
  • @qwabra, I apologize, I meant the data from the object. - Alex
  • still not clear. meaning water.name water.count ? - qwabra
  • @qwabra, yes. It is necessary to transfer somehow their values ​​in the database - Alex
  • two more things confuse me: why php + mysql. as an alternative to nodejs / php + sqlite / json / csv - qwabra

1 answer 1

Look, it's simple enough to read this article . This is unofficial documentation, but it can be useful for understanding. To send ajax to the server, it’s enough in the click handler for the .btn button (although I would recommend not to mix design with logic — i.e., for styles, their classes, and for js logic, for example, with the prefix .js- )

Markup index.html with script

 <!doctype html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="btn js-btn">Кнопка</div> <div class="container"> <div class="test"> <div class="test__name"> </div> <div class="test__price"> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> var water = { name: 'water', count: 200 }; // обработчик клика по кнопке $('.js-btn').on('click', function() { // добавляешь данные в разметку сразу же $('.container').append( `<div class='test'> <div class='test__name'>${water.name}</div> <div class='test__price'>${water.count}</div> </div>` ); // отправляешь ajax запрос на сервер $.ajax({ url: 'test.php', //url серверного обработчика type: 'POST', // тип запроса data: water, // объект с данными берем из замыкания beforeSend: ()=>{}, //этот коллбэк выполняется перед отправкой запроса // этот обработчик выполняется, когда сервер присылает // успешный ответ success: (data)=>{ // data - это тело ответа сервера console.log(data); }, // этот коллбэк выполняется, когда сервер присылает ошибку (коды 300+) error: (xhr)=>{ console.log(xhr); }, // этот коллбэк выполнится в любом случае - при успешном и неуспешном запросе complete: ()=>{ // какие-то действия } }); }); </script> </body> </html> 

Server handler test.php (will work if in one directory)

 <?php // подключение к бд $link = mysqli_connect('localhost', 'user', 'pass', 'db_name'); // в данном примере запрос очень сырой и неподготовленный // обязательно изучи вопрос фильтрации данных перед вставкой в БД (гуглится) $name = $_POST['name']; //поле name из переданного объекта js $count = $_POST['count']; $query = "INSERT INTO table (`name`,`count`) VALUES ('{$name}','{$count}')"; $result = mysqli_query($link, $query); // вывести результат print_r($result); 
  • Is it normal that you get a 404 error (the browser does not see index.php)? Due to POST request. If you put GET, then everything is fine. - Alexey
  • Arrange all on the shelves. Client part separately, server separately. see the updated markup - Maxim K