CodeIgniter Controller - JSON - AJAX

22,150

Solution 1

Firstly, can you try setting the correct header in the Controller?

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

Or better yet:

$this->output->set_content_type('application/json');

As a side note, you should make sure you are always returning JSON data, so I would remove the exit() message and put a default JSON response at the bottom of the method.

Don't forget, when you echo your JSON, you can put return; afterwards to stop any more code running afterwards in that method.

Solution 2

I would like to suggest you about json return. First in your ajax you have to use dataType: 'json'

$.ajax ({
        url: from.attr('action'),
        type: from.attr('method'),
        data: $(from).serialize(),
        dataType: 'json',
    }).done(function(data) {

           ..your code..

    });

CodeIgniter have output class, why don't you use output class to respond to ajax from CI.

$output = array('pls' => 1,
                'msg' => "Password has been sent to given e-mail address"
          );
$this->output->set_content_type('application/json')
             ->set_output(json_encode($output));

Use output class, this is more efficient then echo

I hope it will helps you for better code style.

Share:
22,150
B_CooperA
Author by

B_CooperA

Updated on July 09, 2022

Comments

  • B_CooperA
    B_CooperA almost 2 years

    I'm trying to send a form build with CodeIgniter via AJAX and trying to get the response with JSON. However, I only see the respond when I open my developer tab (I'm not even sure, if that's actually a respond since it's showing both of the json data's).

    All it shows, is the loading spinner, and after that it vanishes.

    Code have been tested without AJAX and it works, so there can't be errors in PHP.

    Here's my controller for resetting the password:

    <?php
    
    Class Users extends CI_Controller {
    
        public function forgot_pass()
        {
    
        if(!$this->input->post('to_email'))
        {
        exit("No data");
        }
    
    
        $this->load->model('user');
        $email = $this->input->post('to_email');
        $email_addr = $this->user->get_email_address($email);
    
    
        if(empty($email_addr))
        {
        echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try  again"));
        }
    
        $this->load->helper('string');
        $new_password = random_string('alnum', 8);
        $this->load->library('phpass'); 
    
        $update_password = array( 'password' => $this->phpass->hash($new_password));
        $update_password = $this->user->update_password($email, $update_password);
    
        $this->load->library('email');
    
        $config['newline'] = '\r\n';
        $this->email->initialize($config);
    
        $this->email->from('[email protected]', 'Your Name');
        $this->email->to($email);  
        $this->email->subject('New password');
        $this->email->message("Hey, " .$email_addr['name']. ". Your new password is: " .$new_password); 
    
        if($this->email->send())
        {
        echo json_encode(array('pls'=>1, 'msg' => "Password has been sent to given e-mail address"));
        }
    
    
    }
    
    }
    ?>
    

    And here's my AJAX call written with jQuery:

    $(document).ready(function() {
    
    $("form#forget_pass_form").on('submit', function(e){
    
                e.preventDefault();
    
                    $("#loading_spinner").show();
                    var from = $(this);
    
                    $.ajax({
    
                        url: from.attr('action'),
                        type: from.attr('method'),
                        data: $(from).serialize(),
                        }).done(function(data) {
    
    
    
                        if(data.pls == 0) {
    
                            $("#forgot-pass-success").hide();
                            $("#forgot-pass-error").show();
                            $("#forgot-pass-error").fadeIn(1000).html(data.msg);
    
                          }
    
                        if(data.pls == 1) {
    
                            $("#forgot-pass-error").hide();
                            $("#forgot-pass-success").show();
                            $("#forgot-pass-success").fadeIn(1000).html(data.msg);
                          }
    
                       $("#loading_spinner").hide(); 
    
                    });
    
                return false;
    
            });
    });