Sam Sam - 3 months ago 15
jQuery Question

fetch value from another page using ajax in codeigniter

I have a foreach loop on index page that displays a list of few ids and in front of each id there is a link (named as detail) which is related to that id only.

The code on index page is

<?php if($request_detail): ?>
<?php foreach($request_detail as $request): ?>
<?php echo $request->requestid; ?>
<a id="link" href="<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>"> Details </a>
<?php endforeach; ?>
<?php endif; ?>

<div id="container">
</div>

<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
$.ajax({
type: "get",
url: "<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>",
success: function(data) {
$('#container').html(data);
}
});
});
</script>


The view i get from above code is

1 details
2 details
3 details


When a user clicks on detail link i wish to fetch the data of that id only from another page and display it under a particular div.

Controller

public function getrequestdetail($id)
{
$data['request_data'] = $this->recruiter_model->get_request_data($id);
$this->load->view('recruiter/request_data_view',$data);
}


Model

public function get_request_data($requestid)
{
/* query is getting executerd here */

return $query->result();
}


The issue is that if i click on first details the id that is being passed in 3 and when i click on other details it gets redirected to another page and has the id 3

But what i want is that


when a user clicks on detail in front of 1 the data of id 1 should get displayed in container div within the same page,

when a user clicks on detail in front of 2 the data of id 2 should get displayed in container div within the same page,

when a user clicks on detail in front of 3 the data of id 3 should get displayed in container div within the same page,


Can anyone please tell how it can be done

Answer

Can anybody else have the Driving license number or same passport numbers as yours. Because they are identities and identities are always unique. Then how can you make all your links having same ID as they are coming from a foreach loop.

You must have to use class for the link. And also you were passing the last ID (last foreach iteration) to your ajax call.

<?php if($request_detail): ?>
    <?php foreach($request_detail as $request): ?>
        <?php echo $request->requestid; ?>
        <a class="link" href="<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>"> Details </a>
    <?php endforeach; ?>              
<?php endif; ?>


$(".link").click(function(e) {
      e.preventDefault(); 
      var url = $(this).attr('href');
      $.ajax({
        type: "get",
        url: url,
        success: function(data) {
          $('#container').html(data); 
        }
      });
    });
Comments