Welcome Guest, Not a member yet? Register   Sign In
Jquery, ajax and json_encode
#1

[eluser]Martin Overgaard[/eluser]
Hi,

I’m trying to accomplish the following with Jquery and AJAX. Jquery is loaded.

1) Use AJAX to insert a new user in a table in my db.
2) Retrieve all users from the table.
3) Display a list (table) with all users, including the one just inserted, in the same view.

My view with AJAX function:

Code:
function(){      
  var querystring = $("form").serialize();

  $.ajax({
    type: "POST",
    url: "https://<homepage>/user/save_user",
    dataType: "json",
    data: querystring,
    cache:false,
    success:
      function(data){  
      var $tr = $('<table></table>');
      $("#user_div").append($tr);
      $.each(data, function() {
      $tr.append('<tr><td>' + data.name + '</td><td>' + data.email + '</td></tr>');
      });
    }
});

...

<div id="user_div"></div>

My controller:
Code:
function save_user() {

  $this->Model->insert_user();

  $users = array($this->Model->get_users();

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

  $this->output->set_output(json_encode($users));
}

My model (to select all users):

Code:
function get_users(){

  $sql = "SELECT * FROM users WHERE is_active =  '1' ";
  
  $query = $this->db->query($sql);

  if ( $query->result() )
    {
      return $query->result();
    }
      else
    {
      return array();
    }
  }

I can save the user in the db. I can get all the users, but I cannot display them in the table with "json_encode". My previous attempts has given me "Undefined" or no results at all. I think, that I miss to convert the json_encode format in the AJAX "success" part, but I don't know how and can't find the answer on the internet.

Any help will be very appreciated.

Best regards
Martin

#2

[eluser]vitoco[/eluser]
I think this may work
Code:
$.each(data, function() {
   $tr.append('<tr><td>' + this.name + '</td><td>' + this.email + '</td></tr>');
});

data is the result json object, this is the iteration object with the attrs.

Saludos
#3

[eluser]Martin Overgaard[/eluser]
Hi vitoco

Solved - works perfect - I'am happy. Many thanks.

Best regards
Martin




Theme © iAndrew 2016 - Forum software by © MyBB