Can't access my Post values send through with

2019-04-13 06:33发布

问题:

EDIT: Removing the 'index.php' with .htaccess creates this probem I just discovered. Now I'm on to resolving it.

EDIT: Problem solved. The javascript was wrong: url: "/login/" It needed a trailing slash.

ORIGINAL: In my home view, I created a form:

<div id="login"><?php 
echo form_open('login');
echo form_input('username', 'Username', 'id="username"');
echo form_submit('submit', 'Login', 'id="login_submit"');
echo form_close();
?></div>

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

$('#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').html(msg);
    }
});

return false;
});

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

class Login extends CI_Controller {

function index()
{
    if($this->input->is_ajax_request())
    {
        echo '<h2>Login succeeded with ajax</h2>';
    }
    else
    {
        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, every other post data is missing. Nothing is put through.

What am I doing wrong?

回答1:

I think your problem could be that you're not actually sending to the correct script. Your url /login doesn't look like it will get to a Codeigniter URL (http://domain.com/index.php/login or http://domain.com/my_app/index.php/login).

Try changing the url to either the full url location of the controller or to a proper absolute path. Either:

url: "http://yourdomain.com/index.php/login",

or

url: "/my_app/index.php/login",

Unless you've rewritten the urls then /login probably won't contact the correct script.



回答2:

This set me in the right direction when i was using PHP and Jquery AJAX to send post values. I am using .htaccess to rewrite the url so as to remove the .php extension. Post values were not being passed on to my sendmail.php file. I solved this by changing the url of the post request from

$.ajax({
                            url:'sendemail.php',
                            method:'post',
                            data:{
                                fname:fname,
                            },
                            success:function (e) {
                                alert(e);
                            }
                        });

to

url:'/sendmail'