Welcome Guest, Not a member yet? Register   Sign In
Post values not send through with ajax and $this->input->post();
#1

[eluser]karimmaassen[/eluser]
In my home view, I created this form:

Code:
<div id="login-signup-form">
    &lt;?php
    echo form_open('login');
    echo form_input('username', 'Username', 'id="username"');
    echo form_password('password', 'Password', 'id="password"');
    echo form_submit('submit', 'Login', 'id="login_submit"');
    echo form_close();
    ?&gt;
</div>

With some basic javascript (thanks to Nettuts) I try to implement some ajax:

Code:
$('#login_submit').click(function() {

    var form_data = {
        username: $('#username').val(),
        password: $('#password').val()        
    };
    
    $.ajax({
        url: "/login",
        type: 'POST',
        data: form_data,
        success: function(msg) {
            $('#login-signup-form').html(msg);
        }
    });
    
    return false;
});

As you can see, it sends the form values to the login controller. The Login controller:

Code:
class Login extends CI_Controller {
    
    function index()
    {
        if($this->input->is_ajax_request())
        {
            echo '<h2>Login succeeded with ajax</h2>';
            echo '<p>Your username is '.$this->input->post('username').'</p>';
        }
        else
        {
            echo '<p>Your username is '.$this->input->post('username').'</p>';
            echo '<p>But your ajax failed miserably</p>';
        }
    }

}

The problem is, it doesn't work. The function `$this->input->is_ajax_request()` outputs FALSE. Ignoring that, `$this->input->post('username')` won't give me the username. It seems that post data isn't put through.


Is this a bug or a known issue or am I just doing something wrong?
#2

[eluser]karimmaassen[/eluser]
The problem is in the javascript. The url needs a trailing slash. So,
Code:
login/
and not
Code:
login

Anyone who knows why this is essential?
#3

[eluser]Ken Verhaegen[/eluser]
[quote author="Kriem" date="1304352975"]The problem is in the javascript. The url needs a trailing slash. So,
Code:
login/
and not
Code:
login

Anyone who knows why this is essential?[/quote]

The problem is that you have specified a relative path for your redirect url to the Ajax controller. You need to make them absolute, or at least relative to the current location. That is to say, for example, if you change your image path from:
Code:
<img src="images/logo.png">
to
Code:
<img src="/images/logo.png">
or
Code:
<img src="http://www.domain.com/images/logo.png">

More info about "why" can be found @ This eFreeDom Question
#4

[eluser]karimmaassen[/eluser]
Thanks! Smile




Theme © iAndrew 2016 - Forum software by © MyBB