user7596840
user7596840

Reputation: 137

How to access array sending from controller to ajax success?

as i am new to codeigniter and ajax please can any one do favor for me.I am sending array from my controller to ajax function but how can i access that array element.I am posting here my code. Thanks in advance.

public function index()
{
    $Modules = $this->General_model->AllMoudules();
    $data['result'] = $this->printTree($Modules);
    $output = array(
    'html'=>$this->load->view("Add_user",$data),
    'data' => $data
    );
    echo json_encode($output);
}

and ajax function

$("#user").on("click",function(){      
var url=static_url+'/User';
$.ajax({
        type:"POST",
        url:url,

        success:function(output)
        {
           $(output).each( function (index, o) {
           alert (o.data);

         });
        }

  });

});

Upvotes: 1

Views: 706

Answers (4)

Swati
Swati

Reputation: 29

Just get the length of array using array.length. Then for loop it

Upvotes: 1

rahul singh
rahul singh

Reputation: 449

You should use ajax datatype as json like this

$.ajax({
        type:"POST",
        url:url,
        dataType: 'json',
        success: function (data) {
            alert(data.key);
        }
    });

Upvotes: 0

parth
parth

Reputation: 1868

To load view in the string you have add third parameter to load view as below:

$output = array(
    'html'=>$this->load->view("Add_user", $data, true),
    'data' => $data
);

To access your ajax response try the below code

success:function(output)
{
    console.log(output.html);
}

Upvotes: 1

Komal K.
Komal K.

Reputation: 470

controller:

  public function index()
        {
            $Modules = $this->General_model->AllMoudules();
            $data['result'] = $this->printTree($Modules);
            $output = array(
            'html'=>$this->load->view("Add_user",$data,true),
            'data' => $data
            );
            echo json_encode($output);
        }

**Javascript:**

$("#user").on("click",function(){      
var url=static_url+'/User';
$.ajax({
        type:"POST",
        url:url,

        success:function(output)
        {
          console.log(output.data);
          console.log(output.html);

         });
        }

  });

Try this.

Upvotes: 2

Related Questions