Part of the EllisLab Network
   
 
ci + jquery
Posted: 18 May 2008 11:12 PM   [ Ignore ]  
Summer Student
Total Posts:  1
Joined  05-14-2008

hello to all,

      I am trying to use jquery with the i. But I can’t find a good tutorial and a sample to study. Can someone give me link or sample. thanks.

Profile
 
 
Posted: 19 May 2008 03:55 AM   [ Ignore ]   [ # 1 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  869
Joined  09-25-2007

http://www.mrforbes.com/wordpress/2007/05/13/a-quick-code-igniter-and-jquery-ajax-tutorial/

I dug this link out for you.

Profile
 
 
Posted: 19 May 2008 04:10 AM   [ Ignore ]   [ # 2 ]  
Sr. Research Associate
RankRankRankRankRank
Total Posts:  4830
Joined  07-14-2006

As gtech pointed out implicitly is that the only time jQuery needs CI is when ajax requests are made. And the only thing that differs in CI is that you have to change setting to allow query strings as most of the ajax needing code/plugins uses query strings. If you don’t want to break the nice urls you can alter the plugins which isn’t that hard to do, just find the ajax call and change the url.

All other jQuery functionalities are for ‘static’ code (html, css).

Profile
 
 
Posted: 19 May 2008 04:35 AM   [ Ignore ]   [ # 3 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  869
Joined  09-25-2007

I have a jquery function in my code that calls codeigiter urls.

code extracted from a view inside < script > tags:

...
function
send_ajax(urlparam)
{
  
$.ajax({
    url
: urlparam + "/" + new Date().getTime(),
    
dataType: "script",
    
cache: false,
    
success: function(html){
      
// call whatever here to display html
    
}
  }
);
};

..
send_ajax('<?=site_url()?>/controller/method/param1/param2');

I have done somthing like above to get my ajax calls working, I only append the time on the end so the urls are unique which saves IE from caching them.

Profile
 
 
Posted: 19 May 2008 06:19 PM   [ Ignore ]   [ # 4 ]  
Grad Student
Avatar
Rank
Total Posts:  38
Joined  08-09-2007

Personally I do everything back and forth with JSON which ends up being a lot more flexible.

Here is the CodeIgniter Controller:

class Ajax extends Controller {

  
var $json_data=Array(
    
'error' => 1,
    
'html' => 'Ajax Error: Invalid Request'
    
);

  function
__construct() {
    parent
::Controller();
    
$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
    
$this->output->set_header('Expires: '.gmdate('D, d M Y H:i:s', time()).' GMT');
    
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    
$this->output->set_header("Pragma: no-cache");
  
}

  
function do_something() {
    $this
->json_data['html'] = $this->load->view('someview', $_POST, true);
    
$this->json_data['error'] = 0;
    
$this->json_data['another_variable'] = 42;
  
}

  
function _output($output) {
    
echo json_encode($this->json_data);
  
}
}


Then in the script…

$.ajax({
    url
: '/ajax/do_something/',
    
type: 'POST',
    
data: {field: value},
    
dataType: 'json',
    
timeout: 8000,
    
success: success_function
  }
);

  function
success_function(json) {
    
if (json.error)
      
alert(json.html);
    else
      $(
'#result_div').html(json.html);

    if (
json.another_variable == 42)
      
alert("I've found the secret of life!");
  
}

Obviously much more useful data can be passed back and forth. Everything in the ‘data’ object on the Javascript side will be in $_POST in CodeIgniter. I have used this setup for two sites now; one with a single AJAX controller that acts as router redirecting to mini-modules; another which uses several controllers just for ajax calls. If you are doing the latter you could setup a parent AJAX controller object which gets extended by all your AJAX controllers.

Profile
 
 
Posted: 20 May 2008 10:45 AM   [ Ignore ]   [ # 5 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  869
Joined  09-25-2007

@onejaguar

thanks for that code snippet thats really useful.

Profile
 
 
Posted: 20 May 2008 01:38 PM   [ Ignore ]   [ # 6 ]  
Grad Student
Avatar
Rank
Total Posts:  43
Joined  02-12-2008

I just use “load” with Code Igniter’s site_url() function.

Here’s the javascript (after loading in jQuery of course):

$(document).ready(function() {
     
   
$("#submitit").click(function() {

        
$("#ajaxresult").load("<?php echo site_url(); ?>/ajax/ajaxloadinfo", {id: id.value});

   
});
   
});

Here’s the form and ajax div:

<div id="ajaxresult">
<?php
//non-ajax result:
if (isset($result))
    echo
$result;
?>
</div>

<
form action="<?php echo site_url(); ?>/ajax/loadinfo" method="POST">
<
input id="id" name="id" />
<
input type="submit" name="submitit" id="submitit" onclick="return false" />
</
form>

This degrades nicely - if javascript is disabled, it loads the “loadinfo” function of the “ajax” controller, otherwise it loads the “ajaxloadinfo” function of the controller. Both functions are basically the same, except “loadinfo” loads the view and passes a variable called $result, and “ajaxloadinfo” just echoes out the result.

The “{id: id.value}” part is the post variables. It assigns the value in the input box (which I named “id”) to $_POST[‘id’], used by the controller.

It took me a long time to figure this out, since there are not many good tutorials on how to use jQuery’s load function with Code Igniter (and the ones that do exist don’t have many examples).

Hope this helps!
Gavin

 Signature 

Zoe and Gavin
Gavin on PHP

Profile
 
 
Posted: 24 May 2008 07:00 PM   [ Ignore ]   [ # 7 ]  
Grad Student
Avatar
Rank
Total Posts:  32
Joined  03-19-2008

@gavin blair:
Can you post here your controller? And if I want to pass more than one input data e.g (‘id’ and ‘address’), how to modify {id : id.value} section?

@onejaguar:
1. Would you mind to post a working example using the method as you described above? I think that would help other people who begin to learn ajax & jquery…

2.

$this->load->view('someview', $_POST, true);

. Could you give more specific information about ‘someview’ script?

 Signature 

Indonesian Job Board will be converted to codeigniter framework

Profile
 
 
Posted: 25 May 2008 12:47 AM   [ Ignore ]   [ # 8 ]  
Grad Student
Avatar
Rank
Total Posts:  43
Joined  02-12-2008

@ardinotow: I have the entire thing here: http://zoeandgavin.com/wpmu/php/2008/05/20/jquery-and-code-igniter/ (there is a download link at the end) If you want to put more than one input, use the syntax: {id: id.value, username: username.value} - just separate with commas. The controller just gets the stuff from the database and echoes out the result. You can use another view and have the controller pull it in, just know that the entire view will go into your div.

 Signature 

Zoe and Gavin
Gavin on PHP

Profile
 
 
Posted: 25 May 2008 09:34 PM   [ Ignore ]   [ # 9 ]  
Grad Student
Avatar
Rank
Total Posts:  38
Joined  08-09-2007
ardinotow - 24 May 2008 07:00 PM

Could you give more specific information about ‘someview’ script?

‘someview’ could be any CodeIgniter “view”. It is bad form to pass $_POST directly into it, in a real world example you would populate a data array as you do for a regular controller; the pass that array. The third “true” parameter makes CodeIgniter return the view as a string, rather than outputting it directly, which enables it to become part of the JSON information you pass back to the JavaScript.

If I get some time I’ll post a more complete example.

Profile
 
 
Posted: 29 May 2008 04:06 PM   [ Ignore ]   [ # 10 ]  
Grad Student
Avatar
Rank
Total Posts:  32
Joined  03-19-2008

Thanks mate…Now I can use codeigniter validation to validate form in ajax way.

I have more question.
Supposed I have one page that contain comment form and comment list. If I post new comment I want to get these instance:
1. The form is validate using ajax, and when no errors occur my new post will be inserted in database then showing ‘input success’ message (all in ajax way).
2. While showing ‘input success’ message, the comment list will refreshed in ajax.

I know how to do the first instance, but I don’t know how to do the second instance. Please anyone help me to get this work.

p.s. Here is my jquery script for doing the first instance

// GLOBAL PARAMS
var file            =    'http://localhost/advoria-ci-FA/comment/do_input_ajax';
var
placeholder        =    '#wrapper';
var
waitholder        =    '#err';
var
waitnote        =    '<img alt="" src="http://localhost/advoria-ci-FA/advoria-assets/gambar/wait.gif" />Please Wait ...';
            
// DOM READY
$(document).ready(function()
{
       
    
// AJAX SUBMIT OPTIONS /
    
var options = {
        beforeSubmit
:    wait,
        
success:        ShowResult,
        
url:            file,
        
type:              'post',
        
dataType:          'json',
        
clearForm:         false,
        
resetForm:         false,
        
timeout:           3000
    }
;
    
// ON SUBMIT FORM
    
$('#ajaxcomment').submit(
        function()
{$(this).ajaxSubmit(options);return false;});
    
//*/
});
            
// SHOW RESULT
function ShowResult(data)
{
    
if(data.success == 'false')
    
{
        
$('#id_user_error').html(data.id_user_error).slideDown('slow');
        $(
'#isi_komentar_error').html(data.isi_komentar_error).slideDown('slow');
        $(
'#rating_error').html(data.rating_error).slideDown('slow');
    
}
    
if(data.success == 'true')
    
{
        
$('#id_user_error').fadeOut('slow').hide();
        $(
'#isi_komentar_error').fadeOut('slow').hide();
        $(
'#rating_error').fadeOut('slow').hide();
        $(
placeholder).html(data.title).slideDown('slow');
    
}
    
$(waitholder).fadeOut('slow').hide();
}        

            
// WAIT MESSAGE
function wait()
{
    
$(waitholder).html(waitnote).fadeIn('fast');
}
            
// CLEAR WAIT MESSAGE
function wipe()
{
    
$(waitholder).fadeOut('fast').html('');
}
 Signature 

Indonesian Job Board will be converted to codeigniter framework

Profile
 
 
Posted: 29 May 2008 05:04 PM   [ Ignore ]   [ # 11 ]  
Grad Student
Avatar
Rank
Total Posts:  38
Joined  08-09-2007

Assuming you are using CSS layout for your comments, something like:

<div id="comment_container">
  <
div class="comment">This is Comment 1</div>
  <
div class="comment">This is Comment 2</div>
</
div>

you could have your “do_input_ajax” routine return another variable containing the processed text of the new comment, so when data.success == ‘true’ it will also pass data.comment_html. In “ShowResult()” add this line to the “true” block:

$('#comment_container').append('<div class="comment">'+data.comment_html+'</div>');

You could also do a second ajax request to get the comment data but less requests is better!

Profile
 
 
Posted: 30 May 2008 10:46 AM   [ Ignore ]   [ # 12 ]  
Grad Student
Avatar
Rank
Total Posts:  32
Joined  03-19-2008

@onejaguar
Awesome, thanks dude.

I Love CI+jquery tongue wink

 Signature 

Indonesian Job Board will be converted to codeigniter framework

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 719, on June 06, 2008 10:16 AM
Total Registered Members: 77530 Total Logged-in Users: 28
Total Topics: 101537 Total Anonymous Users: 3
Total Replies: 544308 Total Guests: 270
Total Posts: 645845    
Members ( View Memberlist )