Slow searching for data with ajax and php

Asked

Viewed 112 times

-1

I have a website, where I have a blog session, but when the system is searching the articles, it takes a while to display

The structure I’m using:

PHP page > Ajax Call (jquery uses ajax to request data via POST (resposata json)) > PHP Controller (filters the function sent by ajax and requests the data for the model) > PHP Model (mysql request)

Example of function to display articles:

Example of Function to show blog Articles:

function buscaTodos(current = 1){
$('.lista_materias').empty();//cleans container of articles
try{
    showLoader();//loader

                $.ajax({  
                    type: 'POST',  
                    url: 'controller/ajax/Artigos.ajax.php', //php controller
                    data: { 
                        'func': "buscaTodos",//php function
                        'current': current
                     },
                    success: function(response) {
                        var res = response.split('[:::]');//parse response of php. Example: 1 to success 0 to error->1[:::]{json response here}

                        if(res[0]==1){//if response is success

                            var obj = JSON.parse(res[1]);//parse json response

                            jQuery.each(obj,function(o, i){
                                //FILL WITH ARTICLES
                                $(".lista_materias").append(
                                    '<div class="col-sm-12 col-md-6 col-lg-4" style="margin-bottom:10px;">'+
                                        '<div class="course-box">'+
                                            '<div class="image-wrap entry">'+
                                                '<img src="images/geral/defer.gif" data-src="images/geral/defer.gif" data-original="images/artigos/'+i['img_box']+'.jpg" data-webp="images/artigos/'+i['img_box']+'.webp" class="imgElastic img-webp" alt="'+i['figcaption']+'" title="'+i['figcaption']+'" class="img-responsive" />'+
                                                '<div class="magnifier">'+
                                                     '<a href="artigos/'+tituloUrl(i['uu'])+'/" title=""><i class="flaticon-add"></i></a>'+
                                                '</div>'+
                                            '</div><!-- end image-wrap -->'+
                                            '<div class="course-details">'+
                                                '<h4>'+
                                                    '<small>Detetive Particular Blog</small>'+
                                                    '<a href="artigos/'+tituloUrl(i['uu'])+'/" title="">'+i['titulo']+'</a>'+
                                                '</h4>'+
                                                '<p class="desc_artigo">'+i['descricao']+'</p>'+
                                            '</div><!-- end details -->'+
                                            '<div class="course-footer clearfix">'+
                                                '<div class="pull-left">'+
                                                    '<ul class="list-inline">'+
                                                        '<li><a href="artigos/'+tituloUrl(i['uu'])+'"><i class="fa fa-user"></i> Detetive Particular André</a></li>'+
                                                        '<li><a href="artigos/'+tituloUrl(i['uu'])+'"><i class="fa fa-clock-o"></i> '+converteDataTimeUsToBr(i['data_criacao'])+'</a></li>'+
                                                        //'<li><a href="artigos/'+tituloUrl(o.url)+'"><i class="fa fa-eye"></i> '+o.contador+' Views</a></li>'+
                                                    '</ul>'+
                                                '</div><!-- end left -->'+
                                            '</div><!-- end footer -->'+
                                        '</div><!-- end box -->'+
                                    '</div><!-- end col -->'
                                );
                            });
                        }else{
                           //showAlert("Bancos",res[1],2);
                           showAlert("Falha ao consultar", "Ocorreu um erro ao consultar os dados. Atualize a página ou entre contato por telefone. \n <span class='code'></span>", 1,'<button type="button" class="btn btn-danger radius_md" data-dismiss="modal">Fechar</button>');
                        }
                        hideLoader();
                    },complete(){
                        getWebp();
                    }
                });



}catch(erro){
    hideLoader();
    showAlert("Falha ao consultar", "Ocorreu um erro ao consultar os dados. Atualize a página ou entre contato por telefone. \n <span class='code'>"+erro.message+"</span>", 1,'<button type="button" class="btn btn-danger radius_md" data-dismiss="modal">Fechar</button>');
    }

}

Artigos.ajax.php

<?php
    require_once("../../autoload.php");
    require_once("../../vendor/autoload.php");
    //echo "<pre>".var_export($_POST,true)."</pre>";

    //Controller
    global $controller;
    $controller = new Artigos_controller();

    //DEFINE QUAL É A FUNCAO
    $func='';
    if(isset($_POST['func']) && strlen($_POST['func'])>0){
        $func=$_POST['func'];
    }else{
        echo '0[:::]Falha interna ao gerar o formulário.';die;
    }

    switch($func){
        case "buscaTodos":buscaTodos($_POST);break;
        case "buscaTodosConta":buscaTodosConta();break;
        default : echo "0[:::]Falha ao processar";break;
    }

    function buscaTodos($post){

        global $controller;

        $exibe = $controller->todosArtigos($post);

        if($exibe[0]){
            echo "1[:::]".$exibe[1];
        }else{
            echo "0[:::]".$exibe[1];
        }
    }
    function buscaTodosConta(){

        global $controller;

        $exibe = $controller->buscaTodosConta();

        if($exibe[0]){
            echo "1[:::]".$exibe[1];
        }else{
            echo "0[:::]".$exibe[1];
        }
    }


?>

Artigos_controller.class.php

<?php
class Artigos_controller{

    private $model;

    public function __construct(){
        $this->model = new Artigos_model();
    }

    public function todosArtigos($p){
        $de = (($p['current']-1)*6);
        $materias = $this->model->todosArtigos($de);

        if($materias[0]){
            if(count($materias[1])>0){
                return array(true,json_encode($materias[1]));
            }
        }else{
            return array(false,$materias[1]);
        }

    }
    public function buscaTodosConta(){
        $qtd = $this->model->buscaTodosConta();

        if($qtd[0]){
            if($qtd[1]>0){
                return array(true,$qtd[1]);
            }
        }else{
            return array(false,$qtd[1]);
        }

    }
    public function buscaDetalhe($id){
        $detalhe = $this->model->buscaDetalhe($id);

        if($detalhe[0]){

                return array(true,$detalhe[1]);

        }else{
            return array(false,$detalhe[1]);
        }

    }
    public function getLinks(){
        $links = $this->model->getLinks();

        if($links[0]){
            return $links[1];
        }else{
            return array();
        }
    }

}
?>

Artigos_model.class.php

<?php

class Artigos_model{

    private $con;

    public function __construct(){
        $this->con = Conn::connect();
    }

    public function todosArtigos($de){
        try{

            if(!$this->con[0]){
                throw new Exception("Falha ao conectar com o banco de dados: ".$this->con[1]);
            }

            $materias = array();

            $query = $this->con[1]->prepare("select id,titulo,descricao,data_criacao,texto,nome_img_box,img_box,figcaption,contador,data_modificado,url as uu from materias order by contador limit $de,6");
            $query->execute();
            $count = $query->rowCount();
           if($count>0){
                $materias = $query->fetchAll();
           }
            return array(true,$materias);

        }catch(Exception $error){
            return array(false,$error->getMessage());
        }
    }

}
?>

1 answer

1

Ever heard of Axios ? It’s an HTTP client based on Promises. Since I met Axios I have never used the Ajax function of Jquery. Axios is much faster and has the simplest syntax in my opinion, I will leave an example of use for you with the link Axios Source Code. Follow the example of use:

Javascript:

axios.post('exemplo.php', {
    varialvel: valor
}).then(function (response) {
    
    //Resposta do PHP
    var response = response.data;
    console.log(response);
    
}).catch(function (error) { });

As you can see it is very simple, in the code above I rewrote the variable that receives the PHP response (sponse) for the value with you in the attribute date, for the sponse comes with other information about the request made.

PHP code:

<?php

    header('Content-Type: application/json');

    $body   = file_get_contents('php://input');
    $post   = json_decode($body, true);

    $response = [

        'error'     => false,
        'mensagem'  => $post['variavel']

    ];

    echo json_encode($response);

In the above example, you can notice that PHP will not receive this data the way it does when we use Ajax with Jquery. But it is not difficult to understand the receipt of this information, briefly we are "picking up" everything that PHP is receiving from Axios in JSON format and converting into a vector for the variable $post, right after that you can use the variable $post as if it were $_POST. I hope it was helpful. Abç amigo !

Follow the link from Source Code of Axios: Axios CDN

Project in Github: Axios Github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.