Return ajax data with php

2

I am creating a modal in ajax where it will return the id and list the information in the modal the problem is that the php returns the "whole page" for ajax and gives me no error in the console, I already tried to use firebug

<script>
    $(function() {
        $(".j_modal").click(function() {
            var id_email = $(this).attr('id');          

            $.ajax({
                url:    'Cad_emails',
                type:   'POST',
                data:   "acao=abre_modal&id_email="+id_email,
                success:    function(dados){
                    console.log(dados);
                }
            });
        });
    });
</script>

<?php 
if ($_POST['acao']) {
    $j_idemail = $_POST['id_email'];

    $resultado = $this->db->get_where('emails', array('i_email' => $j_idemail))->result_array();

    echo 'ok';
}
?>

follows the print from the console where it returns the HTML of the page when it should return an array with the data passed in ajax

I'musingcodeigniter

<?phpdefined('BASEPATH')ORexit('Nodirectscriptaccessallowed');classCad_emailsextendsCI_Controller{public$data_up='';publicfunction__construct(){parent::__construct();$this->load->model('emails_model');}publicfunctionindex(){$this->load->helper(array('text','anexos_helper'));$last_email=$this->db->query("SELECT emails.i_email, emails.'status' FROM 'emails' ORDER BY emails.i_email DESC LIMIT 1")->result_array();

    $regras = array(
        array(
            'field' =>  'assunto',
            'label' =>  'Assunto',
            'rules' =>  'trim|required|max_length[100]|min_length[4]'
        ),
        array(
            'field' =>  'corpo',
            'label' =>  'Mensagem',
            'rules' =>  'trim|required'
        ),
        array(
            'field' =>  'status',
            'label' =>  'Status',
            'rules' =>  'required'
        )
    );

    $this->form_validation->set_rules($regras);

    if ($this->form_validation->run()) {

        $last_idmail = $last_email[0]['i_email']+1;

        $inputs = array(
            'i_email'   =>  $last_idmail,
            'dt_email'  =>  date('Y-m-d H:i:s'),//2015-05-27 16:43:13
            'assunto'   =>  $this->input->post('assunto'),
            'corpo'     =>  htmlspecialchars($this->input->post('corpo')),
            'status'    =>  $this->input->post('status')
        );

        $anexos = upload_anexo('anexos', $last_idmail);

        if ($anexos['file_name'] != ''){
            $data_up = array(
                'i_email'   =>  $last_idmail,
                'legenda'   =>  NULL,
                'arquivo'   =>  $anexos['file_name'],
                'status'    =>  'A'
            );

            $this->db->insert('anexos', $data_up);
        }


        $this->db->insert('emails', $inputs);
        $this->session->set_flashdata('ok', 'E-mail cadastrado com sucesso!');
        redirect(current_url());

    }
    $data['for_emails'] = $this->emails_model->get_emails();
    $data['for_envios'] = $this->emails_model->get_envios();
    $this->load->view('cad_emails/emails_plincipal', $data);
}

}

/* End of file Cad_emails.php */
/* Location: .//C/wamp/www/emails_crebas/app/controllers/Cad_emails.php */

The content of the driver is more likely that the problem is not in it, since it has no interaction with ajax that is only in the view.

    
asked by anonymous 08.06.2015 / 19:59

2 answers

1

Web frameworks usually load the site template by default. So, to return a json you need to check the documentation for the framework version of your project, and add a rule in the class that renders the site to ignore the template.

I believe this link can help you.

Note that the framework itself is already prepared to deal with this type of data: (The code below was taken from the codeignite doc itself.)

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => 'bar')));

//$this seria o escopo do seu controller

There is also the possibility of forcing PHP to close, but this method is not as pretty as the previous one.

die(json_encode($meusDados));
    
30.11.2016 / 21:13
1

I use CodeIgniter and sometimes I also need to get some information via ajax. What I recommend you do is create a controller special only for ajax requests. I would make a controller named ajax.php :

<?php
class Ajax extends CI_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function cad_emails(){
     //TODO CONTEÚDO DO CAD_EMAILS
    }
}
?>

Javascript:

<script>
    $(function() {
        $(".j_modal").click(function() {
            var id_email = $(this).attr('id');          

            $.ajax({
                url:    '<?php echo base_url();?>ajax/cad_emails',
                type:   'POST',
                data:   {acao: "abre_modal", id_email: id_email},
                success:    function(dados){
                    console.log(dados);
                }
            });
        });
    });
</script>

<?php 
if ($_POST['acao']) {
    $j_idemail = $_POST['id_email'];

    $resultado = $this->db->get_where('emails', array('i_email' => $j_idemail))->result_array();

    echo 'ok';
}
?>

Put all the code in the cad_emails() function of the controller ajax . But always remember not to put $ this-> load-> view () or something that loads templates, otherwise it will also send via ajax all the content.

    
31.12.2016 / 20:01