Return ajax data with php

Asked

Viewed 1,230 times

2

I am creating a modal in ajax where it will return the id and lists the information in modal the problem is that php returns the "full page" to ajax and gives me no error in the console, I have 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';
}
?>

follow the console print where it returns the page’s HTML when it should return an array with the passer data in ajax inserir a descrição da imagem aqui

I’m using codeigniter

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Cad_emails extends CI_Controller {

public $data_up = '';

public function __construct()
{
    parent::__construct();
    $this->load->model('emails_model');
}

public function index()
{
    $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 */

It follows the contents of the controller but I believe that the problem is not in it, because it has no interaction with ajax that is only in the view.

  • 1

    You can put the html of the form tbm?

  • Cad_emails possesses what?

  • @rray am not using form just a button with the class j_modal

  • @Maiconcarraro Cad_emails is the main controller, has nothing associated to doubt only a registration of a form, more if it is necessary to put the content

  • 1

    It is probably returning the entire page, because in the CI controller you are using you are not only returning a view with the necessary content. You can change your controller to return a JSON and work with JSON in javascript as well.

  • I posted the contents of the controller so you can take a look

  • Where are you returning the ID and list?

  • the script that receives the data via POST is on the same page that submits the request? I speak this due to the code you posted.. If it is this way it is obvious that it will always give error... The if ($_POST['action']) { should also block the other codes.. Still not a good practice.

  • I think the view q you’re returning should tbm be returning the system layout.. I don’t know in codeigniter, but in cakephp we can say $this->layout = false; and display only the view.

Show 4 more comments

3 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 that that 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 to force the termination of PHP execution, but this method is not as beautiful as the previous.

die(json_encode($meusDados));

1

I use the CodeIgniter and sometimes I also need to get some information via ajax. What I recommend you to do is to create a controller special only for ajax requests. I would make a controller called 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 function cad_emails() controller’s ajax. But always remember not to put for example the $this->load->view() or something that loads templates, otherwise it will also send all the content via ajax.

0

You can do it like this:

<?php
class Ajax extends CI_Controller{

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

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

<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';
}
?>

Browser other questions tagged

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