V
V
vladimirr892018-04-20 07:41:47
Laravel
vladimirr89, 2018-04-20 07:41:47

How to load articles with ajax by button on laravel?

I'm new to these things, please tell me how to correctly set up loading article previews using ajax when clicking on the "more articles" button?
1. So I created a router from where I will pick up news

Route::get('/getnews', ['as' => 'ajax.getnews', 'uses' => '[email protected]']);

2. I created a page that displays previews of 4 pieces and assigned the address to the "more articles" button (the controller that displays articles on the view is made and works)
3. Next, I need to make a controller for Ajax, on which I have a blunt
public function morenews(Request $request){	
    $more_news = News::paginate(4);
    if($request->ajax())
    {
      $data = ... (что конкретно сюда писать не понимаю)
      return responce($data, 200);
    }
  }

4. Further, in general, the porridge is incomprehensible in my head.
Maybe someone has a normal sensible example or tell me how to bring it to the end?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2018-04-20
@Eridani

Here, in general, is a crooked-ass example, which I quickly threw at random. 5ad9a0a12c296505520641.png
Here is the code

spoiler
<?

/*
 * Демонстрация старого способа работы с базой данных MySQL
 */
 
# Соединение
mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
 
# Выбор базы данных
mysql_select_db('paginate') or die('Не могу выбрать базу данных');
 
 


// количество записей, выводимых на странице
$per_page=2;

  // получаем номер страницы
  if (isset($_POST['page'])) $page=($_POST['page']-1); else $page=0;
  // вычисляем первый оператор для LIMIT
  $start=abs($page*$per_page);	


?>
<?
if($_POST['ajax'] == 1) {
  $data = '';
  // составляем запрос и выводим записи
  // переменную $start используем, как нумератор записей.
  $q="SELECT * from news LIMIT $start,$per_page";
  $res=mysql_query($q);
  while($row=mysql_fetch_array($res)) {
    $data[] = $row;
  }	
    
  die(json_encode(array('res' => 'success', 'data' => $data)));
}
?>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=win-1251">
  </head>
  <body>
    <div class="news">
      <?
        // составляем запрос и выводим записи
        // переменную $start используем, как нумератор записей.
        $q="SELECT * from news LIMIT $start,$per_page";
        $res=mysql_query($q);
        while($row=mysql_fetch_array($res)) {
          echo ++$start.". Название новости:  ".$row['heading']."<br>\n";
        }
    
      ?>
    </div>
    <button id="showmore" data-page="2">Показа Ышо</button>
    
    
    <script src="https://yastatic.net/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $('#showmore').click(function(){
        
        var page = parseInt($(this).attr('data-page'));
        var offset = parseInt(page);
        $.ajax({
          type: "POST",
          url: '/',
          data: {'ajax' : 1, 'page' : page},
          dataType: 'json',
          success: function(data){ 
          console.log(data);
          
          if(data.res == 'success'){   
            $(data.data).each(function(){
              $('.news').append('Название новости: ' + this.heading + '<br/>');
              
            })
            $('#showmore').attr('data-page', page+1);
          }
          else{

          }
          },
          error: function(error) {
          console.log(error);
          },
          beforeSend: function() {
          console.log('loading...');

          },
          complete: function() {
          console.log('complete!');
          }
        });
        
        return false;
      })
    </script>		
  </body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question