Php AJAX不能在CodeIgniter表单提交中执行

Php AJAX不能在CodeIgniter表单提交中执行,php,ajax,json,forms,codeigniter,Php,Ajax,Json,Forms,Codeigniter,我是AJAX编程新手,正在从事一个应该使用AJAX的项目 我将PHP与CodeIgniter框架结合使用,我希望创建表单,当提交表单时,它将返回一条成功消息,而无需重新加载页面,这就是我选择ajax的原因。但是从我编写的代码来看,它可以在不阅读AJAX的情况下工作,它会移动到另一个页面,当然,不会显示任何成功消息 所以我的主要问题是我的AJAX表单提交无法执行,我不明白为什么 任何帮助都将不胜感激 这是我的controller.php public function index() {

我是AJAX编程新手,正在从事一个应该使用AJAX的项目

我将PHP与CodeIgniter框架结合使用,我希望创建表单,当提交表单时,它将返回一条成功消息,而无需重新加载页面,这就是我选择ajax的原因。但是从我编写的代码来看,它可以在不阅读AJAX的情况下工作,它会移动到另一个页面,当然,不会显示任何成功消息

所以我的主要问题是我的AJAX表单提交无法执行,我不明白为什么

任何帮助都将不胜感激

这是我的controller.php

public function index()
{
    $this->form_validation->set_rules('advice', 'Advice', 'required');
    $data["CatId"]=$this->viewbook_model->getCategory();
    $this->ckeditor->basePath = base_url().'assets/ckeditor/';
    $this->ckeditor->config['toolbar'] = array(
                    array( 'Source', '-', 'Bold', 'Italic', 'Underline', '-','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-','NumberedList','BulletedList' )
                                                        );
    $this->ckeditor->config['language'] = 'it';
    $this->ckeditor->config['width'] = '730px';
    $this->ckeditor->config['height'] = '300px';            

    //Add Ckfinder to Ckeditor
    $this->ckfinder->SetupCKEditor($this->ckeditor,'../../assets/ckfinder/'); 

    if($this->session->userdata('is_logged_in')){
    $this->load->model('feedback_model');
    $data['feedback'] = $this->feedback_model->get_subject();

    $advice_list = $this->feedback_model->get_subject();
    $x = 0;
    foreach($advice_list AS $al)
    {
        $data['feedback'][$x] = array(
            'CategoryAdviceId' => $al['CategoryAdviceId'],
            'CategoryAdviceName' => $al['CategoryAdviceName']
        );
        $x++;
    }

    $data['booklist'] = $this->feedback_model->find($this->session->userdata('username'));
    $book_list = $this->feedback_model->find('username');
    $y = 0;
    foreach($book_list AS $bl)
    {
        $data['booklist'][$y] = array(
            'AssetTitle' => $bl['AssetTitle'],
            'bi' => $bl['bi']
        );
        $y++;
    }

    $data['adviceid'] = $this->feedback_model->get_adviceId();
    $adviceid_list = $this->feedback_model->get_adviceId();
    $x = 0;
    foreach($adviceid_list AS $adv)
    {
        $data['adviceid'][$x] = array(
            'AdviceId' => $adv['AdviceId']
        );
        $x++;
    }

    $page_content["page_title"] = "Send Feedback";
    $page_content["title"] = "Suggestion and Feedback";
    $page_content["icon_title"] = "home";

    $menu_params["current_navigable"] = "Feedback";
    $menu_params["sub_current_navigable"] = "";

    $page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
    $page_content["content"] = $this->load->view("feedback", $data, true);
    $page_content["navmenu"] = $this->load->view("nav_menu", $data, true);

    $this->load->view("template/main_template", $page_content);
    }else{
        redirect('login/restricted');
    }
}
//this is the function that sent data to model and return json to view for display success message
function insert_to_db()
{
    $this->feedback_model->insert_into_db();

    echo json_encode('true');
}   
这是我在view.php中的表单代码

<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">

                 <div class="control-group">

                    <!--FEEDBACK TYPE-->

                        <label class="span2 control-label" >Feedback for</label>

                        <div class="controls with-tooltip"> 
                        <select  class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
                            <option value="" disabled selected>Choose Your Feedback For..</option>
                         <?php 
                            for($x = 0 ; $x < count($feedback) ; $x++) 
                            { ?> 
                                <option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
                            <?php 
                            } ?>
                        </select>
                        </div>  
                </div>

            <!--SUBJECT-->  
                <div class="control-group">
                    <label for="limiter" class="control-label">Subject</label>

                    <div class="controls">
                        <input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.."  />
                        <p class="help-block"></p>
                    </div>                      
                </div>

            <div id="emptybox"></div>
            <!--CHOOSE BOOK-->  
            <div id="showupbox" style="display: none;">             
                <div class="control-group">
                    <label class="control-label">Choose Book</label>
                        <div class="controls">
                            <select  class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
                                <option value="" disabled selected>Choose Your Feedback For..</option>
                             <?php 
                                for($y = 0 ; $y < count($booklist) ; $y++) 
                                { ?> 
                                    <option value="<?php echo $booklist[$y]['bi']?> - <?php echo $booklist[$y]['AssetTitle']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
                                <?php 
                                } ?>
                            </select>
                        </div>
                    </div>
            </div>  
            <!--ADVICE-->   
                <div class="control-group">
                    <label for="limiter" class="control-label" >Suggestion</label>

                    <div class="controls">
                    <?php echo $this->ckeditor->editor("Advice",""); ?>
                      </div>                        
                </div>

            <!--Type Advice ID-->
            <div class="control-group hidden">
                    <label for="limiter" class="control-label" >Sugg</label>

                    <div class="controls">
                    <?php 
                            for($x = 0 ; $x < count($adviceid) ; $x++) 
                            { ?> 
                        <input type="text" class="span5" maxlength="50" id="TypeAdviceId" name="TypeAdviceId" value="<?php echo $adviceid[$x]['AdviceId']?>"/>
                    <?php
                            } ?>
                        <p class="help-block"></p>
                    </div>
            </div>  
            <div class="control-group hidden">
                    <label for="limiter" class="control-label" >Sugg</label>

                    <div class="controls">
                        <input type="text" class="span5" maxlength="50" id="NoBook" name="NoBook" value="-"/>
                        <p class="help-block"></p>
                    </div>
            </div>  

                <!--div class="alert alert-success">  
                      <a class="close" data-dismiss="alert">×</a>  
                      <strong>Success!</strong> Thanks for your feedback!   
                    </div--> 

                <div class="bton1">
                    <button class="btn btn-primary round" type="submit" id="btnSubmit">Submit</button>
                    <button class="btn btn-primary round" type="refresh">Reset</button>
                    </div>
        </form> 
这是我的脚本和AJAX代码:

$(document).ready(function() {
    //this is for CKEDITOR validation
    for(var name in CKEDITOR.instances) {
        CKEDITOR.instances["Advice"].on("instanceReady", function() {
            // Set keyup event          
            this.document.on("keyup", updateValue);
            // Set paste event
            this.document.on("paste", updateValue);     
        }); 

        function updateValue() {
            CKEDITOR.instances["Advice"].updateElement(); 
            $('textarea').trigger('keyup');
        }
   } 
    //this is my form validation
    $("#feedback_form").validate({
     ignore: 'input:hidden:not(input:hidden.required)',
        rules: {
            CategoryAdviceSelect:"required",
            Subject:"required",
            Advice:"required",
            BookSelect:{
                    required: function(element){
                    return $("#CategoryAdviceSelect").val()==1;
                }
            }
        },
        messages: {
            CategoryAdviceSelect:"Please select one of category advice",
            Subject:"This field is required",
            Advice:"This field is required",
            BookSelect:"This field is required",
        },
        errorElement: "span",
        errorPlacement: function (error, element) {
              if ($(element).attr('name') == 'Advice') {
                  $('#cke_Advice').after(error);
              } else {
                  element.after(error);
              }
          },
        highlight: function(element) {
            $(element).parent().addClass("help-block");
        },
        unhighlight: function(element) {
            $(element).parent().removeClass("help-block");
        }
    });
    //this is my ajax submission
    $("#btnSubmit").click(function() {
     var formURL = $(this).attr("action");
     var methodtype = $(this).attr("method");
     $.ajax({
        url : formURL,
        type: methodtype,
        data : {
            CategoryAdviceSelect:CategoryAdviceSelect,
            Subject:Subject,
            Advice:Advice,
            BookSelect:BookSelect,
            TypeAdviceId:TypeAdviceId,
            NoBook:NoBook
               },
        ajaxOptions: {
            dataType: 'json'
        },
        success : function(data){
                setTimeout(function() {location.reload(true)}, 1700);
                $('#success .success-content span').html('Thankyou for your <b>feedback</b>');
                $('#success').fadeIn();
                setTimeout(fade_out, 1200);
            }

        });
        return false;
    });
});

不要使用表单标签,只需使用:in codeigniter即可

<?php $attr = array('id'=>'feedback_form', 'name'=>'feedback_form', 'class'='form-horizontal', 'novalidate'=>'novalidate');?>
<?php echo form_open('feedback/feedback/insert_to_db', $attr);?>
更改AJAX功能更改按钮单击事件以形成提交事件

$("#feedback_form").submit(function(e) {
 e.preventDefault();
 var formURL = $(this).attr("action");
 var methodtype = $(this).attr("method");
 $.ajax({
    url : formURL,
    type: methodtype,
    data : {
        CategoryAdviceSelect:CategoryAdviceSelect,
        Subject:Subject,
        Advice:Advice,
        BookSelect:BookSelect,
        TypeAdviceId:TypeAdviceId,
        NoBook:NoBook
           },
    ajaxOptions: {
        dataType: 'json'
    },
    success : function(data){
            setTimeout(function() {location.reload(true)}, 1700);
            $('#success .success-content span').html('Thankyou for your <b>feedback</b>');
            $('#success').fadeIn();
            setTimeout(fade_out, 1200);
        }

    });
    return false;
});

feedback/feedback/insert_to_db这是正确的url吗?我想是的,因为它在没有AJAX的情况下可以正常工作,url@Nouphal.Mhave您是否检查了任何js错误。使用萤火虫