loading with ajax in codeigniter while running SQL Server job

0

I'll tell you, I've been developing a PHP platform with codeigniter 3.0, I'm connected to a local SQL Server database, in which I have a job called Automatic. This job is executed using the function of the model "execute_job":

CONTROLLER

public function ejecutar() // Enfocado a UCF - Consolidar BBDD
{
    $this->load->model('modelo');
    $this->modelo->ejecutar_job();
}

MODEL

 function ejecutar_job()
    {
            try
            {       
                    $query = $this->db->simple_query("EXEC msdb.dbo.sp_start_job 'Automatico';");
                    return 1;
            }

            catch(Exception $e)
            {
                    echo $e;
                    return 0;
            }


    }

So far so good, but since it is a job that takes more less 2 min. I need a way for the platform to distinguish when it has finished its process. For this I thought about AJAX, implementing the following code:

AJAX in VISTA

<script type="text/javascript">
    $("form").submit(function(event)
    {
        var url="<?php echo base_url("index.php/welcome/ejecutar");?>";
        event.preventDefault();
        $.ajax({
        type: 'POST',
        url: url,

        beforeSend: function(){
                $('#cargando').html("<img src='<?php echo base_url('imagenes/cargando.gif');?>'>");
            },
        })

        .done(function(data) {
        alert('Envío Satisfactorio!');
                location.href = "<?php echo base_url('index.php/welcome/descargar_consolidado');?>";

    })
    })
</script>

This code should put an image.gif while the action is running and when it is finished, it would jump to the ".done" function redirecting to the file download page.

The problem is: the execution of the job if it is done, and it also redirects to the download page, but I can not keep the image "loading" all the execution time. Rather just try to drive the AJAX jumps to '.done' without having finished the execution time, which causes the download document is not ready.

It may be a very simple error or problem, but I can not solve it. If they give me help, it would be great ...

Greetings!

    
asked by estimaops 10.10.2017 в 18:52
source

1 answer

1

I have already solved it, I discovered that when working with JOBS in SQL Server, since you do not have any type of return from the JOB (unless you parameterize it), you can not wait for it to be done ... I finally made a query to determine if the job ends, and another to determine its final status. When I call the JOB, I call these queries and everything solved (I did not know that there were certain tables that controlled the actions of the jobs) ... if someone has the same problem, my solution was:

CONTROLLER:

public function ejecutar() // Consolidado de documentos del servicio 
    {
        if($this->session->userdata('username')){
            $this->load->helper('url');
            $this->load->model('modelo');
            $valor=$this->modelo->ejecutar_job();
            $aux_termino['valor'] = 5;
            $aux_status['valor'] = 10;
            while($aux_termino['valor'] == 5){                          //5 = no ha terminado, 1 = ha terminado
                $termino=$this->modelo->comprobar_termino_job1();
                $aux_termino=json_decode(json_encode($termino),true);   //pasar desde objecto json a array[]
                sleep(4);                                               //para no saturar el servidor
            }
            $status=$this->modelo->comprobar_termino_status_job1();
            $aux_status = json_decode(json_encode($status),true);
            if($aux_status['valor'] == 1  || $aux_status['valor'] == '1'  ){
                redirect('welcome/descargar_consolidado');
            }
            else{
                redirect('welcome/error_ejecucion');
            }
        }
        else{
            redirect('login');
        }
    }

MODEL

 function ejecutar_job() // CONSOLIDACIÓN DE BASES DE DATOS DEL SERVICIO
        { 
            $t = 2;
                try
                {       
                        $query = $this->db->simple_query("EXEC msdb.dbo.sp_start_job 'Automatico';");
                        sleep($t);
                        return 1;
                }

                catch(Exception $e)
                {
                        echo $e;
                        return 0;
                }


        }


  function comprobar_termino_job1(){
        $consulta= "SELECT valor = 
                    CASE when 
                    (select
                    tabla1.last_executed_step_id  
                    from  msdb.dbo.sysjobactivity tabla1 
                    left outer join 
                    msdb.dbo.sysjobs_view tabla2 
                    on 
                    tabla1.job_id = tabla2.job_id 
                    where 
                    tabla2.name = 'Automatico'
                    and tabla1.start_execution_date = 
                        (select MAX(tabla1.start_execution_date) 
                        from msdb.dbo.sysjobactivity tabla1 
                        left outer join 
                        msdb.dbo.sysjobs_view tabla2 
                        on
                        tabla1.job_id = tabla2.job_id 
                        where tabla2.name='Automatico')) is null 
                        then 5 else 1
                        end ";
                    $query = $this->db->query($consulta);
                    return $query->row();
}

function comprobar_termino_status_job1(){
    $consulta="SELECT run_status as valor
                from 
                msdb..sysjobhistory tabla_historial 
                inner join 
                msdb..sysjobs tabla_jobs 
                on 
                tabla_historial.job_id = tabla_jobs.job_id 
                where tabla_jobs.name='Automatico' 
                and 
                tabla_historial.instance_id = 
                (select max(instance_id) from msdb.dbo.sysjobhistory 
                where step_name='Automatico')";
                $query = $this->db->query($consulta);
                return $query->row();
}

and the view:

<html>
<body>
<div id="container">
        <div class="col-md-1"></div>
        <div class="col-md-10"> 
            <div class="jumbotron">
                    <h1>
                        <center>Subida exitosa <span class="glyphicon glyphicon-ok"></span></center>
                    </h1>
                    <center><p>
                        La carga de archivos ha sido exitosa, para continuar presione el botón <i>"Consolidar"</i>
                            <br><br>
                            <!--<form action="<?php //echo base_url("index.php/welcome/ejecutar"); ?>" method="post">
                                <input type="submit" id="" name="submit" class="btn btn-primary" value="Consolidar">
                            </form>-->
                        <form action="<?php echo base_url('index.php/welcome/ejecutar'); ?>" method="post" id="formulario">
                            <input type="submit" value="Consolidar" class="btn btn-danger">
                        </form>
                            <div id="cargando" class="cargando">
                            </div>              
                    </p>
                    </center>
            </div>
        </div>
<br>
</div>
</body>
<script type = "text/javascript" src="<?php echo base_url('assets/js/jquery-3.2.1.js');?>"></script>
    <script type="text/javascript">
        $("#formulario").submit(function(event){
            document.getElementById('formulario').style.display='none'; 
            $('#cargando').html("<img src='<?php echo base_url('imagenes/cargando.gif');?>'>");
        });
    </script>
</html>
    
answered by 17.11.2017 в 13:09