The site is implemented on Smarty .
There was a desire to add a search on the site.
Faced a problem: I can’t understand how to pass from the searchproductAction , what it returns, it works correctly, but I don’t understand how to use its value. SearchController.php :

 function indexAction($smarty){ $rsCategories = getAllMainCatsWithChildren(); $text = isset($text) ? $text : null; $smarty->assign('text', $text); $smarty->assign('pageTitle', 'Поиск'); $smarty->assign('rsCategories',$rsCategories); loadTemplate($smarty, 'header'); loadTemplate($smarty, 'search'); loadTemplate($smarty, 'footer'); } function searchproductAction(){ $search_box = $_POST['search_box']; $search_box = trim($search_box); $search_box = mysql_real_escape_string($search_box); $search_box = htmlspecialchars($search_box); if (empty($search_box)) { $resData['success'] = 0; $resData['message'] = 'Вы ничего не ввели в окно поиска'; echo json_encode($resData); return; } if (strlen($search_box) < 3) { $resData['success'] = 0; $resData['message'] = 'Слишком короткий поисковый запрос'; } else if (strlen($search_box) > 128) { $resData['success'] = 0; $resData['message'] = 'Слишком длинный поисковый запрос'; } else { $text = 0; $res = searchTextProduct($search_box); if (mysql_affected_rows() > 0) { $search_text = mysql_fetch_assoc($res); $num = mysql_num_rows($res); $resData['success'] = 1; $resData['message'] = "По запросу $search_box найдено совпадений: $num"; do { // Делаем запрос, получающий ссылки на продукты $res1=getLinkSearchProduct($search_text); if (mysql_affected_rows() > 0) { $product = mysql_fetch_assoc($res1); } $text = $text . '<p><a href="/product/'.$product['id'].'/">'.$product['name'].'</a></p>'; } while ($search_text = mysql_fetch_assoc($res)); return $text; } else { $resData['success'] = 0; $resData['message'] = 'По вашему запросу ничего не найдено'; } } } 

Search form:

 <form method="post" action="/search/"> <input type="text" name="search_box" id="search_box" class='search_box' placeholder="Что искать?" /> <input type="submit" value="Поиск" class="search_button" onclick="searchProduct();"/><br /> </form> 

javascript:

 function searchProduct() { var search_box = $('#search_box').val(); var postData = {search_box:search_box}; $.ajax({ type: 'POST', async: true, url: "/search/searchproduct/", data: postData, dataType: 'json', success: function (data) { if (data['success']) { alert(data['message']); document.location = '/search/'; } else { alert(data['message']); } } }); } 

search.tpl:

 <div class="text-info"> {if isset($text)} По вашему искомому слову найдено: <br> {$text} {/if} </div> 

Everything should work as follows: the user enters a word, receives an alert with the number of products found, with the given word, then the shell ( search.tpl ) to the file, displays the link (s) and name (s) of the product (s)

  • what a fiasco. if you use smarty then why the hell are you writing html generation directly to php? Generate the template in a string, write the output $resdata['content'] and output it $resdata['content'] when you receive a response. without any redirections there. - teran
  • why do you even use mysql_affected_rows and the outdated mysql extension 10 years ago? why check isset in the template. templates are made to simplify the maximum layout. there is no need to write there. - teran
  • Thank you, I understood what my mistake will be trying to fix. - Anton Kutepov

1 answer 1

I will try in the morning to sum up my comment yesterday. using AJAX, you call the searchproductAction method. There is no need to build the logic so that once this method returns json, to the next html and so on. Let it always return json.

Simplify the challenge:

 function searchProduct() { var data = { search_box: $('#search_box').val() }; $.post("/search/searchproduct/", data, function(result){ alert(result.message); if(result.success){ $("#results").html(result.content); } }); } 

Thus, if successful, we expect that the content field will contain the html-code of the list of search results. And we do not need redirects here. If you use transitions to another page, then the request must be recorded in the session on the server side. And after the transition to the desired action, use this saved value. So the question is, really you need to open another page, or just place the result on the current one.

Start the search method by filling in the default response, and finish sending it.

 function searchproductAction(){ $search_box = ....; $result = ['sucess' => 0, 'message' => "По вашему запросу ничего не найдено" ]; ..... echo json_encode($result); } 

when processing the query string, you will only change the error message. Next, go to the formation of the results start a new template search_results.tpl

 {foreach $products as $p} <p><a href="/product/{$product.id}">{$product.name}</a></p> {/foreach} 

set the result to 1 and the corresponding message, extract the records from the database, and transfer them to the template. Then run the template and write the result of its execution in the result array

  $result['success'] = 1 $result['message'] = "...."; ..... $smarty->assign('products', $products); $result['content'] = $smarty->fetch('search_results.tpl');