baitas212123
baitas212123

Reputation: 151

How to pass data from controller to view via json on CodeIgniter?

I'm trying to pass data from controller to view via json, after event in my main login page. Login page js looks like:

$('#submit_loginform').live('click',function(){

    $("#error_message").fadeIn(500).html("<img src='images/loaders/loader2.gif' alt='loading' />"); // debug message area

    //var login_name  = $("#login").val();
    //var pass        = $("#pass").val();

    var data        = {
        name        : $("#login").val(),
        password    : $("#password").val(),
        ajax        : 1
    }

    $.ajax({
        url: "home/login_validation", // my home controller function "login_validation:
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function (data) {

            if(data.message){
              alert(data.message);
            } 
        },
        error: function (e) {
            console.log(e.message);
        }
    });

 });

And my controller looks like:

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

class Home extends CI_Controller {

    public function index(){

       $data = array(
            "text" => "Welcome",
            "time" => date("Y/m/d")
       );

       $this->load->view('home_view.php', $data);
    }

    public function login_validation(){

        $array = array(
            "message" => "all things are beutiful"
        );

        $data['json'] = json_encode($array);
        $this->load->view('login_view.php', $data);        
    }

}

and after all, when I'm trying to submit data, I should receive an alert with text "all things are beutiful", but the alert is not "poping up".

Btw i checked it with firebug for response, and the response is the same HTML code from my home_view file.

What is wrong? What I should do to receive normall response from controller?

Upvotes: 1

Views: 8762

Answers (1)

dm03514
dm03514

Reputation: 55962

your ajax function is expecting json as a response.

You could accomplish this by echoing json string directly, or having your view render one.

public function login_validation(){

    $array = array(
        "message" => "all things are beutiful"
    );

    $data['json'] = $array;
    echo json_encode($data);          
}

// js
alert(response.json.message);

Upvotes: 1

Related Questions