Welcome Guest, Not a member yet? Register   Sign In
HOW TO DISPLAY JSON IN HTML
#1

[eluser]johanriyan[/eluser]
hallo master,

i have error when i'am showing data using json array.

here my controller

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

class Welcome extends CI_Controller {

/**
  * Index Page for this controller.
  *
  * Maps to the following URL
  *   http://example.com/index.php/welcome
  * - or -  
  *   http://example.com/index.php/welcome/index
  * - or -
  * Since this controller is set as the default controller in
  * config/routes.php, it's displayed at http://example.com/
  *
  * So any other public methods not prefixed with an underscore will
  * map to /index.php/welcome/<method_name>
  * @see http://codeigniter.com/user_guide/general/urls.html
  */
public function index()
{
  $this->load->view('welcome_message');
}

public function ajax()
   {
          $data = array(
                'name' => 'johan',
                'hobby' => 'music',
  'interest' => 'PHP'
            );
   foreach($data as $key => $val){
  $data2= $key." : ".$val."<br>";
   }
// set text compatible IE7, IE8
header('Content-type: text/plain');
// set json non IE
header('Content-type: application/json');
header("content-type: application/json; charset=utf-8");
print json_encode ($data2);
}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

and my view

Code:
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt; Ajax Exmaples! &lt;/title&gt;
  &lt;!--Load JQUERY from Google's network --&gt;
[removed][removed]  
[removed]
$(document).ready( function() {
cek();
});

function cek(){
    $.ajax({
        url: '&lt;?php echo base_url('index.php/welcome/ajax');?&gt;',
        cache: false,
dataType: 'json',
        success: function(msg){
            $("#data").html(msg);
        }
    });
    var waktu = setTimeout("cek()",100);
}
  [removed]
&lt;/head&gt;
&lt;body&gt;
<div id="data"></div>
&lt;/body&gt;
&lt;/html&gt;

just 1 display in my view. last array
interest : PHP.

Please help.
#2

[eluser]CroNiX[/eluser]
They way you have it set up in your loop, $data2 will only be the very last value from your $data array. Each loop overwrites the previous value with the new value. Not sure what the purpose of that loop is anyway. Why not just json_encode($data)?
#3

[eluser]johanriyan[/eluser]
could you give me example. please.




Theme © iAndrew 2016 - Forum software by © MyBB