简体   繁体   English

ajax表单在codeigniter中提交

[英]ajax form submit in codeigniter

In my simple ajax login form. 在我简单的ajax登录表单中。 I tried to validate my form using ajax in codeigniter and return the message as json data. 我试图在codeigniter中使用ajax验证表单,并将消息作为json数据json

The below are my codes. 以下是我的代码。 It gives correct output. 它给出正确的输出。 my question is 我的问题是

I used submit path in both the form and ajax url . 我在form和ajax url中都使用了提交路径。 If don't use it in both places, it won't work well. 如果不在两个地方都使用它,它将无法正常工作。 Is it a good practice? 这是一个好习惯吗? Is there any other way to do this? 还有其他方法吗?

Any suggestions ? 有什么建议么 ?

view_login.php view_login.php

<body>
    <?php
    $this->load->helper('form');
    echo form_open('login/submit', 'id="login_form"');
    echo form_input('name', '', 'id="name"');
    echo form_password('password', '', 'id="password"');
    echo form_submit('button', 'Submit', 'id="submit"');
    echo form_close();
    ?>

</body>

custom.js custom.js

var url = 'http://localhost/ci_test_ajax/';
function user_login(data){
return $.ajax({
    url: url+'login/submit',
    type: 'POST',
    async: false,
    dataType: 'json',
    data: data
});
}
$(function () {
var url = 'http://localhost/ci_test_ajax/';
$('#login_form').submit(function (e) {
    e.preventDefault();
    var data = $('form#login_form').serialize();
    user_login(data).done(function(data){
        console.log(data);
    });
});
});

submit function in login.php login.php中提交功能

function submit()
{
    $this->load->library('form_validation');
    $this->form_validation->set_rules('name', 'Name', 'trim|xss_clean|required');
    $this->form_validation->set_rules('password', 'Password', 'xss_clean|min_length[4]|required');
    if($this->form_validation->run() == TRUE)
    {
        echo json_encode('yes');
    }
    else
    {
        echo json_encode('no');
    }
}

It was not at all a good practice, If you are using codeigniter, try adding the base_url(); 这根本不是一个好习惯,如果您正在使用codeigniter,请尝试添加base_url();。 to a js variable in the header section before your custom.js file include, then access the js variable; 在您的custom.js文件包含之前在标头部分中的js变量中,然后访问js变量;

<script>
var base_url = '<?php echo base_url(); ?>'; 
</script>

if your are submitting your form through ajax , than why use 2 url you can use only one. 如果您要通过ajax提交表单,那么为什么要使用2个url,则只能使用一个。

Try something like this 试试这个

$(function () {
    $('#login_form').submit(function (e) {
        var url = this.action;
        $.ajax({
            url: url,
            type: 'POST',
            async: false,
            dataType: 'json',
            data: $(this).serialize()
        }).done(function(data){
            console.log(data);
        });
        return false;
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM