Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading a view after an ajax call, CodeIgniter

I have an ajax call from javascript to a method in a controller, the method in the controller should be loading a view(like, show a new page on the screen), Although everything seems ok, the new view doesn't seem to load on the screen. I cannot use header or windows.location because, i am passing an array variable, containing data to be used in the view.

The page is visible under the Network tab (preview sub tab, while selecting the ajax) of the Chrome debugging console. But the main screen stays as it is.

If somebody has faced a similar issue, or has a solution, please help me.

Thanks!!

like image 572
Archer Avatar asked Mar 01 '13 18:03

Archer


2 Answers

Ok here is what you are doing wrong.

when you request the page using ajax it does not return you that page.

When you use $this->load->view('pagename',$datapassed); it loads the view and that's why you see nothing.

What you have to do is use

$data=$this->load->view('pagename',$datapassed, TRUE);

What it will do is, it will return that page and save it in $data after that you can print it using

$this->set_output($data); 

and receive this in ajax result and load it in a div.

and if you want to refresh the whole page you can use

$(body).html(result);

You have to understand that you need to send the html page by supplying that third parameter in load view.

like image 131
Muhammad Nasir Avatar answered Oct 20 '22 19:10

Muhammad Nasir


In controller class

function get_view_ajax()
{
   $data['username] = $_POST['username];
   $response = $this->load->view('radius/radius_corporate_graph',$data,TRUE);
   echo $response;
}

In view file where you initiate ajax call

$('#button').click(function(){
var username = $('#username').val();

$.ajax({
   type:'POST',
   url:"<?php echo base_url(); ?>controller_name/get_view_ajax/",
   data: "username="+username,
   success:function(msg){
    $("#div_result").html(msg);
   },
   error: function(result)
   {
      $("#div_result").html("Error"); 
   },
   fail:(function(status) {
      $("#div_result").html("Fail");
   }),
   beforeSend:function(d){
    $('#div_result').html("<center><strong style='color:red'>Please Wait...<br><img height='25' width='120' src='<?php echo base_url();?>img/ajax-loader.gif' /></strong></center>");
   }

  }); 
});

<div id="div_result">
<a href="#" id="button">Click here </a>  

Another view file to be loaded on controller function (extra_info.php) as refered on get_view_ajax function

<h1>This page is called from ajax function </h1>
like image 11
Dipen Avatar answered Oct 20 '22 19:10

Dipen