Part of the EllisLab Network
   
 
CI and Ajax requests with jQuery
Posted: 16 February 2007 09:54 AM   [ Ignore ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  326
Joined  02-16-2007

Hello,
I’ve been wanting to use a PHP framework for awhile now, and will hopefully use CI on my next project. I’m a little confused on how to handle ajax posts and requests with the framework though, and I don’t want to use a helper class because it creates obtrusive code. I’d rather keep all my client side code seperate from the server side. In the video demo a form page basically posts back to itself right? If my form posts to blog/newentry by default for example, can I call the same path with an ajax post? If so how is the callback handled?

Does that make any sense? smile

Does anyone have any examples of CI working with jQuery?

 Signature 

@litzinger
blog

Profile
 
 
Posted: 16 February 2007 10:20 AM   [ Ignore ]   [ # 1 ]  
Summer Student
Total Posts:  9
Joined  10-05-2006

Hi tilzinger,

Derek’s tutorial is a good example on how to handle Ajax posts.
Basically you would need a different page to post to via Ajax, so your script would need to intercept the form submission, then post the data to your script that handles the ajax call and display the result. I assume you want to use jQuery - so the $.post() function is your friend. It has a callback argument for a function to be executed after the Ajax call was successful. In Derek’s tutorial, he uses the application/ajaxsearch controller for that.

As for CI and jQUery: One of my first projects using these two is an photographer showcase using unobstrusive JS. Real simple page, I was focussing on maximum degradability.
http://utjonok.de/
There are still some issues I’d like to fix, such as reenabling the back button etc., but it works for now.

Good luck!
Bernd

Profile
 
 
Posted: 16 February 2007 11:38 AM   [ Ignore ]   [ # 2 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  326
Joined  02-16-2007

Oh, I see. So I just need an extra function for the ajax requests, not a whole new page.

I noticed in the js file the variable ‘base_url’, but it isn’t defined anywhere in the JS file. How is the value that is defined in the config.php file being passed to the JS file??

 Signature 

@litzinger
blog

Profile
 
 
Posted: 16 February 2007 12:19 PM   [ Ignore ]   [ # 3 ]  
Summer Student
Total Posts:  4
Joined  07-14-2006

You can do it like this. Place it inside script tags at html head.

var base_url = <?=base_url()?>
    </script>
Profile
 
 
Posted: 16 February 2007 05:42 PM   [ Ignore ]   [ # 4 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  366
Joined  04-27-2006

maybe if someone is interested, here is a small jquery ajax codigniter example…
$(’#your_div’).load(”<?=site_url().”/ajax/test/some_parameter222”?>”);
this calls the output of the ajax/test controller function into your_div

the problems that are not solved yet is it does not work with foreign characters…
and opera browser makes problems, sometimes it works, but sometimes the ajax info just blinks shortly and is away…


the controller ‘ajax.php’

<?php

class ajax extends Controller {
    
function Ajax()
    
{
        parent
::Controller();
        
$this->load->helper('url');    
    
}
    
function index()
    
{    
        $this
->load->view('ajax');
    
}

    
function test($data=FALSE)
    
{    
        
echo "hello this is the function ajax/test....";
        echo
"<br>you called the function <br>".site_url()."/ajax/menu/".$data;
        echo
"<br> and you passed the parameter $data...";
    
}
}
?>

the view ‘ajax.php’ (change ‘>’ to ‘<’ bevor script…)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>Ajax test</title>

>
script src="http://jquery.bassistance.de/starterkit/lib/jquery.js" type="text/javascript"></script>
>script type="text/javascript">
        function
ajax_load()
        
{
                
$('#your_div').load("<?=site_url()."/ajax/test/some_parameter222"?>");
        
}    
  </script>

</head>

<
body>
    <
div id="your_div">ajax content will be here loaded...</div>
    
<
p><a href="#" onClick="ajax_load()">look</a></p>

</
body>
</
html>
Profile
 
 
Posted: 16 February 2007 07:03 PM   [ Ignore ]   [ # 5 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  515
Joined  12-05-2006

This is an AJAX example to generate dependant drop down (select):

CONTROLLER: dropdown.php

<?php
class Dropdown extends Controller {
    
    
function Dropdown()
    
{
        parent
::Controller();
        
$this->load->helper(array('form', 'url'));
    
}
    
    
function index($options=null)
    
{    
        $data[
'first_options'] = array(         
                    
'1'  => 'Italy',
                      
'2'    => 'Brazil',
                );

        
$options!=null ? $data['options'] = $options : '';
        
$this->load->view('ddown', $data);
    
}
    
//-------------------------------------------------------------
    
    
function prova()
    
{
            
//this is for a demo and uses arrays
            //you can also build options with DB queries
            
$data['options_1'] = array('1'=>'topolino',
                                       
'2'=>'pippo',
                                       
'3'=>'minnie',
                                       
'4'=>'paperone');
                                      
            
$data['options_2'] = array('1'=>'brazilian',
                                       
'2'=>'girls',
                                       
'3'=>'rock!');
            
            
$options ='';                      
            if (
$_POST['first_select']!='') //$_POST['first_select'] is the post variable you sent via AJAX call
            
{
                $parent
= $_POST['first_select'];
                switch(
$parent)
                
{
                    
case 1:
                        
$data['options'] = $data['options_1'];
                    
                        break;
                    
                    case
2:
                        
$data['options'] = $data['options_2'];
                    break;
                
}
                
                
foreach ($data['options'] as $key=>$value)
                
{
                $options
.= '<option value="'.$key.'" class="dynamic">'.$value.'</option>';
                
}
        
                
echo $options;
            
}
                        

    }    
}

?>

VIEW: ddown.php

<html>
<
head>
<
title>Dynamic Dropdown</title>
>
script src="http://www.your_path/jquery.js" type="text/javascript"></script>
>script type="text/javascript">
     
function
test()
{
    
var valore = $("#first_select").val();
    $.
ajax({
           url
: "<?=base_url();?>dropdown/prova",
           global:
false,
           
type: "POST",
           
async: false,
           
dataType: "html",
           
data: "first_select="+ valore, //the name of the $_POST variable and its value
           
success: function (response) //'response' is the output provided by the controller method prova()
                       
{
                       
//counts the number of dynamically generated options
                       
var dynamic_options = $("*").index( $('.dynamic')[0] );
                    
//removes previously dynamically generated options if they exists (not equal to 0)
                       
if ( dynamic_options != (-1)) $(".dynamic").remove();
                    $(
"#second_select").append(response);
                    $(
".first").attr({selected: ' selected'});
                   
}
                   
          }
);
    
          return
false
}
</script>
</head>
<
body>
<
h1>Dynamic Dropdown</h1> by <a href="http://www.4webby.com">4webby.com</a>
<?=form_open('')?>
<p>
    <
select name="first_select" id="first_select" onchange="test()">
        <
option value="0">browse</option>
        <
option value="0">----------------</option>
        
<?php
        
if (isset($first_options))
        
{
            
foreach ($first_options as $key=>$value)
            
{
                
echo '<option value="'.$key.'">'.$value.'</option>';
            
}
        }
        ?>
    
</select>
    
    <
select name="second_select" id="second_select">
        <
option value="0" class="first">browse</option>
        <
option value="0">----------------</option>
    </
select>
</
p>
<?=form_close()?>
</body>
</
html>

What I found difficult in the beginning was to debug the ajax calls. For this purpose I suggest you FireBug

 Signature 

FreakAuth_light: pluggable & extendable authentication library that works on CI 1.5.X

CI SWIFT MAILER: 44% less memory than PHPMailer at double speed

Using Zend Framework components in Code Igniter

Profile
 
 
Posted: 22 February 2007 12:40 AM   [ Ignore ]   [ # 6 ]  
Summer Student
Total Posts:  19
Joined  12-26-2006

great post danfreak.. helped a lot !

Profile
 
 
Posted: 22 February 2007 03:03 AM   [ Ignore ]   [ # 7 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  515
Joined  12-05-2006
Rokster - 22 February 2007 12:40 AM

great post danfreak.. helped a lot !

It took me a bit of effort to make it work as well, ‘cause it was my first attempt to do an ajax call mayself, so I thought it could help somebody else.

Did you try it? Did it work?

Dan

 Signature 

FreakAuth_light: pluggable & extendable authentication library that works on CI 1.5.X

CI SWIFT MAILER: 44% less memory than PHPMailer at double speed

Using Zend Framework components in Code Igniter

Profile
 
 
Posted: 22 February 2007 07:20 AM   [ Ignore ]   [ # 8 ]  
Research Assistant
RankRankRank
Total Posts:  303
Joined  10-17-2006

Check my blog for some more stuff on CI with jQuery. I put together a helper for CI that builds a autocomplete input thingy in jquery.

Profile
 
 
Posted: 22 February 2007 03:28 PM   [ Ignore ]   [ # 9 ]  
Summer Student
Total Posts:  15
Joined  01-31-2007

Haven’t used it myself yet, but my feed delivered the following reference to PQuery this morning.

http://www.ngcoders.com/pquery/user_guide/

Sort of a PHP wrapper for jQuery (vague enough?).

greg

Profile
 
 
Posted: 24 February 2007 08:08 AM   [ Ignore ]   [ # 10 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  886
Joined  03-06-2006
nmweb - 22 February 2007 07:20 AM

Check my blog for some more stuff on CI with jQuery. I put together a helper for CI that builds a autocomplete input thingy in jquery.

I didn’t see a link to download the helper ... the source was supposed to be available after jQuery 1.1 was released ... is it available now?

Thanks lots.  I really like the autocomplete demo.

EDIT: Sorry, found the download link here.

 Signature 

Corozal, Belize | Linux.bz | Using Kubuntu Linux 7.10 | CodeIgniter 1.5.3

Profile
 
 
Posted: 14 October 2009 08:41 AM   [ Ignore ]   [ # 11 ]  
Summer Student
Total Posts:  4
Joined  10-08-2009

I like Dans reply, but it is not dynamic if you have like x categories in the database due to the switch($parent) {. So to solve this you can write something like this:

$data[‘options’] = $data[‘options_’ . $parent];

Then you don’t need the switch section at all grin

Thanks Dan for the initial example

Paal

Profile
 
 
   
 
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 11:15 AM
Total Registered Members: 120316 Total Logged-in Users: 56
Total Topics: 126437 Total Anonymous Users: 3
Total Replies: 664888 Total Guests: 498
Total Posts: 791325    
Members ( View Memberlist )