• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple ajax query

#1
[eluser]cip6791[/eluser]
Hello,

I was wondering if someone can help me figure out how to include the queried data into
Code:
<div id="cont"></div>
Now the jquery adds something like this:
Code:
string(2) "50" array(1) { [0]=> object(stdClass)#18 (6) { ["id"]=> string(1) "1" ["filename"]=> string(8) "filename" ["title"]=> string(5) "title" ["width"]=> string(2) "50" ["height"]=> string(2) "60" ["color"]=> string(3) "red" } } {"status":"ok","content":"50"}

I would also like to know if this is the best way to query the database and display data with ajax.

Thanks

view
Code:
&lt;form method="post" acti&gt;
      <label for="title">Stuff</label>
      &lt;input type="text" name="value" id="value" value="" /&gt;
  
      &lt;input type="submit" name="submit" id="submit" /&gt;
   &lt;/form&gt;

js file
Code:
$("#submit").click(function (e) {
e.preventDefault();
        var width = $('#value').val();
        $.ajax({
            url: "http://site.com/index.php/welcome/get_items",
            data: {
                width: width
            }
        }).done(function(data) {
   $('div#cont').text(data);
        }).fail(function() {
            alert('Failed!')
        });

    });

Controller
Code:
public function get_items()
    {
            $this->load->model('home_model');

             $this->load->library('form_validation');
                $this->form_validation->set_rules('width', 'Width', 'trim|required|xss_clean');
                $width = $_GET['width'];

            $one_exp = $this->home_model->one_exp($width);
            if($one_exp != false){
     //$html = '<ul>';
                    foreach($one_exp as $exp) {
                            $html = $exp->width;
                    }
                    //$html .= '</ul>';
                    $result = array('status' => 'ok', 'content' => $html);
                    echo json_encode($result);
                    exit();
            }else{
                    $result = array('status' => 'no', 'content' => 'nothing here');
                    echo json_encode($result);
                    exit();
            }

    }

model
Code:
function one_exp($width) {
           $query_str = "SELECT * FROM files WHERE width=?";
     $query = $this->db->query($query_str, array($width));

  if($query->num_rows() > 0) {
      foreach($query->result() as $item) {
    $data[] = $item;
   }
       return $data;
        } else {
                return false;
        }
    }

#2
[eluser]Kiran K[/eluser]
Hi ,

Instead of $('div#cont').text(data), its better to use $('div#cont').html(data).

Here you need to decode the data , which is the ajax request response before outputting it into html dom.

try using using

obj = JSON.parse(data);
console.log(obj .item);

Thanks


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.