Reputation: 217
Here is my code in controller. I want grab this results into ajax success part. my question how to display results in ajax after using JSON.parse() function, can some one help me with loop; json code is something like this [{'id:1'},{info:name}]
???
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$query = $this->db->get('pages');
$data = array();
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
}
$json = json_encode($data);
echo $json;
}
ajax part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
alert(msg);
// $.each($.parseJSON(msg), function() {
// $('#results_box').html(this.id + " " + this.info);
// });
}
});
Upvotes: 0
Views: 703
Reputation: 8991
First remove that dataType form your $.ajax(), and then add a correct content-type header in php like:
header('Content-type: application/json');
This way, jQuery will parse your json correctly.
Now, you can do something like:
success: function(res){
$.each(res, function(el) {
console.log(el.id);
console.log(el.info);
});
}
Upvotes: 0
Reputation: 11106
just change
dataType: "text",
to
dataType: "json",
and jQuery is doing the parsing.
[EDIT]
supposed you have: [{'id':1,'info':'name'},{'id':2,'info':'nom'} ]
(your json in your post is slightly unusable and not the result of an json_encode of an array)
...
success: function(msg){
var id = msg[0].id;
var info = msg[0].info;
...
There's no error handling and no exception handling in this code which I regard as necessary!
Upvotes: 1