codeigniter + Ajax (亲测)

(E文,没时间翻译)

首先做一个Ajax的helper,下面是说明,很简单,粘贴复制就可以了。。。

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

function is_ajax()
{
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}

?>

Copy the following code into a file. Save the file as ajax_helper.php and save in your application/helpers/ folder.

Load it if you need if by:

Normal loading

This is pretty much how we normally include helpers. This is the best approach unless you would use the ajax helper most of the time.

$this->load->helper('ajax');

Autoloading

Open your config.php file located at application/config/ . Look for this line.

$autoload['helper'] = array();

Add yours to the list

$autoload['helper'] = array('ajax');

You should not add _helper when adding it to the autoload[‘helper’] array.

下面是详细说明: 初中英语够你看懂以下内容了 (最后一行还有测试页面呢~~)

AJAX can be seen almost everywhere on the web. Yahoo uses it. Google uses it. My boss uses it. My grandmother uses it — well maybe not but that shouldn’t stop you from using it.

Here’s an awesome tutorial to use AJAX with CodeIgniter.

This tutorial assumes that you have a form set-up like so:

<?php echo form_open(current_url(), array('id' => 'registration_form'));?>
<label for="username">Username: </label>
<input type="text" class="span-2" value="" name="username" id="username" /><br />

<label for="first_name">First Name: </label>
<input type="text" value="" name="first_name" id="first_name" /><br />

<label for="last_name">Last Name: </label>
<input type="text" value="" name="last_name" id="last_name" /><br />

<label for="desc">Password: </label>
<input type="password" value="" name="password" id="password" /><br />

<label for="desc">Repeat Password: </label>
<input type="password" value="" name="passconf" id="passconf" /><br />

<label for="desc">Email: </label>
<input type="text" value="" name="email" id="email" /><br />

<label for="register"> </label>
<input type="submit" value="Register" name="register" id="register" class="update" />
</form>

The form starts with the usual form helper , form_open(). The rest is pretty much normal.

Now with the Javascript. In this tutorial, we will use jQuery

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Now we do AJAX

Javascript

<script type="text/javascript">
$(document).ready(function() {
 $('#registration_form').submit(function(){
         $.post("<?php echo site_url(current_url());?>", {
             username: $('#username').val(), 
             first_name: $('#first_name').val(),
             last_name: $('#last_name').val(),
             password: $('#password').val(),
             passconf: $('#passconf').val(),
             email: $('#email').val(),
          },
          function(data){
                  alert(data);
          }
  );
  return false;
 });
});
</script>

Explanation

$.post("<?php echo site_url(current_url());?>", {

The fourth line of the previous code will request to the current url. This means that if you are on ‘/this/page/’, it will request to ‘/this/page/’.

username: $('#username').val(), 
first_name: $('#first_name').val(),
last_name: $('#last_name').val(),
password: $('#password').val(),
passconf: $('#passconf').val(),
email: $('#email').val()

The above will be the information we will post. For example, username: $('#username').val() will pass the value of the element with the id, username. In our case, that would be one of the inputs.

function(data){
    alert(data);
}

The above is the callback. From here we accept the response from our request. In our case, we alert the response.

CodeIgniter

function ajax_with_codeigniter()
{
       $this->load->library('form_validation');
       $this->load->helper(array('ajax', 'form'));

       $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
       $this->form_validation->set_rules('first_name', 'First Name', 'required');
       $this->form_validation->set_rules('last_name', 'Last Name', 'required');
       $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
       $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
       $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

       if ($_POST)
       {
                if (is_ajax() AND $this->form_validation->run() === TRUE)
                {
                    echo "Registration Successful";
                }
                else
                {
                    echo validation_errors(' ',' ');
                }
        }
        else
        {
         $this->load->view('code/ajax_with_codeigniter/ajax_with_codeigniter');
        }
}

Explanation

$this->load->library('form_validation');
$this->load->helper(array('ajax','form'));

The above code will load the library ajax helper, the form helper and the form validation library.

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
 $this->form_validation->set_rules('first_name', 'First Name', 'required');
 $this->form_validation->set_rules('last_name', 'Last Name', 'required');
 $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
 $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
 $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

The above code is how we set rules. Pretty normal if you have used CodeIgniter in the past.

if ($_POST)
{
    if (is_ajax() AND $this->form_validation->run() === TRUE)
    {
        echo "Registration Successful";
    }
    else
    {
        echo validation_errors(' ', ' ');
    }
}
 else
{
    $this->load->view('code/ajax_with_codeigniter/ajax_with_codeigniter');
}

 

The last piece of code checks for anything POST ed. Remember that we are requesting to the same method so we should check for anything POST ed before we output anything. This conditional statement is only used because of the situation. You normally won’t have this checkpoint.

There’s something POST ed

When we know that there was something POST ed, we check if the request was done via the ajax_helper. This is just some check if we only want AJAX requests. The second part of the condition is if the data passed passes the validation rules we set up. If it checks out fine, we send our message, “Registration successful”. If not, we send the errors.

Nothing was POST ed

When we know that nothing was POST ed, we load the view. This pretty much activates when we just loaded the page.

Demo

You can visit our AJAX with CodeIgniter demo .

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.