Part of the EllisLab Network
   
 
Returning text from function called via Ajax
Posted: 03 July 2010 08:51 AM   [ Ignore ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  514
Joined  04-29-2007

Does anyone know or can point me to instructions on how I can return a text string from a function which has been called via Ajax?  I’ve looked into ‘responseText’ but this doesn’t seem to give me any control over what text is returned.

Is there another way to receive text back from an Ajax call?

TIA

 Signature 

music, wood, code, zen | @carvingCode

Profile
 
 
Posted: 03 July 2010 09:52 AM   [ Ignore ]   [ # 1 ]  
Grad Student
Avatar
Rank
Total Posts:  99
Joined  02-11-2009

ajax always receive data in a string.

Profile
 
 
Posted: 03 July 2010 12:47 PM   [ Ignore ]   [ # 2 ]  
Lab Technician
RankRankRankRank
Total Posts:  1158
Joined  03-30-2009

You will find using jQuery for handling ajax request alot easier, and cross browser support. When returning/processing any ajax request you will want to use json to respond.

//jQuery
$("#some_form").submit(function(){
    event
.preventDefault();
  $.
ajax({
      url
'<?php echo site_url('controller/method');?>',
      
dataType'json',
      
type'POST',
      
data: $(this).serialize(),
      
success: function(data){
        
if(data.response =='true'){
            alert(data
.message)//change alert to updated DOM somewhere
        
}
      }
,
      
error: function(){
          alert(
'Something major failed');
      
}
  }
);
});

//In controller/method

$data['response''false'//default response
if($this->form_validation->run())
{
   $data[
'some_field'$this->input->post('some_field');
   
$data['response''true'// form submission worked
   
$data['message']  'successful ajax request string';
}
echo json_encode($data); 
 Signature 

Useful CI Links
Base Controllers by Phil Sturgeon
Cache Library by Phil Sturgeon
Carabiner css/js management by tonydewan

Profile
 
 
Posted: 03 July 2010 03:29 PM   [ Ignore ]   [ # 3 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  514
Joined  04-29-2007

Thanks, pickupman.  Excellent example!  I tweeked it to my needs and things working as expected.

Of course, I was all around this solution in my trials, trying various datatypes.  Not JSON.  smile

 Signature 

music, wood, code, zen | @carvingCode

Profile
 
 
Posted: 05 July 2010 09:29 AM   [ Ignore ]   [ # 4 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  514
Joined  04-29-2007

To followup, here’s a link to a brief article I wrote about my implementation.

 Signature 

music, wood, code, zen | @carvingCode

Profile
 
 
   
 
 
‹‹ Ajax and CI      help with routes ››