I will try to describe as much as possible the essence of my problem, what I am trying to do and what I have already tried to do, so ..
There is a catalog of goods and I need that by clicking on a certain element of the list, product cards related to the subject of the selected list element are displayed.
I know how to implement the withdrawal of product cards. And without Ajax, it would look like this:
There would be a link passing the section name with the "GET" method.
<a href = "?pc">Комплектующие ПК</a>
The php code that displays the item cards in the right place:
if (isset(($_GET['pc']))) { $query = "SELECT * FROM `tableName`"; $result = $pdo->query($query); foreach ($result as $array) { $name = $array['name']; //наименование товара $price = $array['price']; //цена товара include 'card.php'; //подключение шаблона "карточки товара" } }
And the product card template "card.php":
<div class = "card"> <div class = "card-header fl"> <p class = "product-name fl-al-c"> <?php echo $name; ?> </p> <!-- Наименование --> </div> <div class = "card-content fl"> <img src = "images/img.png" alt = "#"> </div> <div class = "card-footer fl-al-c"> <p class = "price"> <?php echo $price; ?> </p> <!-- Цена товара --> </div> </div>
But now I need to do the same, but with the help of Ajax, which I began to study more recently.
I built the following Ajax request:
Sel.on('click', function(){ Ext.Ajax.request({ url: 'php/handler.php', method: 'POST', params: { category: 'pc' }, success: function (response) { var objAjax = Ext.decode(response.responseText); //запись полученных данных в objAjax var elementsInObjAjax = (Object.keys(objAjax).length); //количество элементов в objAjax console.log("Ajax request: success // (sendAjaxRequest)"); console.log(objAjax); for (var i = 0; i < elementsInObjAjax; i++) { name = objAjax[i]['name']; //наименование price = objAjax[i]['price']; //цена $('#products').load('php/card.php'); } }, failure: function () { console.log("Ajax request: failure // (sendAjaxRequest)"); } }); });
And I wrote the following handler code:
if ((isset($_POST['category'])) && (!empty($_POST['category']))) { $tableName = $_POST['category']; $query = "SELECT * FROM `$tableName`"; $result = $pdo->query($query); $data = array(); foreach ($result as $array) { array_push($data, $array); } echo json_encode($data); }
As can be seen from the console, all data was received.
But as a result, only one card is displayed. The code in the body of the for loop is repeated as many times as there are elements in the array received from the server. But the following fragment:
$('#products').load('php/card.php');
It seems to work only once or simply replaces the previous data in the map with new ones.
I’ve been surfing the internet for quite a while looking for an answer to the topic of processing the response and inserting it into the page, but I haven’t found anything. Apparently bad looking.