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.

Description .

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.

enter image description here

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.

  • Jquery.load just loads the data from the URL. You already have all the data in Json, this stops the interaction with the server and the data from Json is output in html. - u_mulder 8:38 pm
  • It's not clear by the way why you use jquery and extjs together. - u_mulder 8:40 pm
  • for adding code to the end of the container $ (""). append ("<div> </ div>") and to the beginning of $ (""). preppend ("<div> </ div>") - Vitaly Shebanits

2 answers 2

The $ .load documentation says that after the request, the entire container is replaced with the html response from the server.

One way is to drop a callback into $ .load itself, which upon completion completes the container, and, accordingly, clear the container when you first call to avoid overfilling with “old” data.

 const $products = $('#products') function concatProducts (newHtml) { let oldHtml = $products.html() $products.html(oldHtml + newHtml) } // до главного вызова (цикла) $products.html('') // далее получаем html и конкатенируем $products.load('php/card.php', concatProducts) 

And so - there are many ways - from any jQuery ajax method / axios type libraries to the classic fetch / XMLHttpRequest , it depends on tasks and needs.

In your case, if html comes from the server - you just need to insert it into the container, two options - either concatenate (if there are several requests for each card), or update the container html-code (if there is one request for a pack of cards).

In the case of a json response, it is enough to create a html card template and draw, for example, using underscore / php templates or plain html.

    You can create the following function to display a product card:

     function renderCARD(t) { var Card = { tag: 'div', cls: 'card fadeIn', id: id, children: [{ tag: 'div', cls: 'card-header fl pc-c', children: [{ tag: 'p', cls: 'product-name fl-al-c', html: name }] },{ tag: 'div', cls: 'card-content fl', children: [{ tag: 'img src = "images/products/computer-parts/no-image.png" alt = "#"', }] },{ tag: 'div', cls: 'card-footer fl-al-c', children: [{ tag: 'p', cls: 'price', html: price }] }] }; Ext.core.DomHelper.append(t, Card); } 
    • In the Card object is written html markup card product, it is a "template".
    • Using the class Ext.core.DomHelper, you can output the template to the place written to the variable "t".

    Next, you need to call the renderCARD (t) function in a loop:

     for (var i = 0; i < elementsInObjAjax; i++) { name = objAjax[i]['name']; price = objAjax[i]['price']; id = objAjax[i]['id']; renderCARD(products); }