首页 文章

在CodeIgniter中插入表单的模式中的AJAX

提问于
浏览
2

我一直在努力争取这个约4个小时,我试图有一个模态下拉(Twitter引导模式),其中包含一个创建公司的表单 . 这是在CodeIgniter中构建的 .

我遇到输入类型=“提交”和输入类型=“按钮”的问题 .

我只有1个必填字段,即公司名称 . 如果我使用input type =“button”,验证将在模态内正确激活,但是表单只会插入公司名称,以及company_id,user_id,active和cdate .

现在如果我使用input type =“submit”,所有数据插入都很好 . 但是,验证中断并且在单击“创建公司”后出现“无法找到页面”,但数据仍在插入 .

有任何想法吗?谢谢! AJAX新手......

我的AJAX功能:

$(document).ready(function(){

  $('#create_btn').live('click', function(){
      //we'll want to move to page specific files later

    var name = $('#name').val();

    $.ajax({
        url: CI_ROOT + "members/proposals/add_client",
        type: 'post',
        data: {'name': name },
        complete: function(r){
          var response_obj = jQuery.parseJSON(r.responseText);

          if (response_obj.status == 'SUCCESS')
          {
              window.location = CI_ROOT + response_obj.data.redirect;
          }
          else
          {       
            $('#error_message2').html(response_obj.data.err_msg);
          }
        },
    });     


  });

});

我的控制器功能处理插入:

function add_client()
{

    $this->form_validation->set_rules('name', 'Company Name', 'trim|required|xss_clean');

    load_model('client_model', 'clients');
    load_model('industry_model');

    $user_id = get_user_id();
    $company_id = get_company_id();

    if (!$user_id || !$company_id) redirect('home');

    if ($_POST)
    {

        if ($this->form_validation->run() == TRUE)
        { 

        $fields = $this->input->post(null , TRUE);


        $fields['user_id'] = $user_id;
        $fields['company_id'] = $company_id;
        $fields['active'] = 1;
        $fields['cdate'] = time();


        $insert = $this->clients->insert($fields);

            if ($insert)
            {
                $this->message->set('alert alert-success', '<h4>Company has been added</h4>');
                header('location:'.$_SERVER['HTTP_REFERER']);
            }
            else
            {
                $this->message->set('alert alert-error', '<h4>There was an issue adding this Company, please try again</h4>');
            }                   


        }


        else
        {  
            $err_msg =  validation_errors('<div class="alert alert-error">', '</div>'); 
            $retval = array('err_msg'=>$err_msg);
            $this->ajax_output($retval, false);
        }

    }

    $this->data['industries'] = array(0=>'Select Industry...') + $this->industry_model->dropdown('industry');   

    $this->insertMethodJS();
    $this->template->write_view('content',$this->base_path.'/'.build_view_path(__METHOD__), $this->data);           
    $this->template->render();
}

最后,我的看法:

<div class="modal hide fade" id="milestone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width: 600px !important;">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Add a Company</h3>
  </div>

  <div class="modal-body">

    <?php echo form_open_multipart(base_url().'members/proposals/add_client', array('class' => '', 'id' => 'client_form'));?>   

    <div id="error_message2"></div> 

    <div class="row-fluid">
        <div class="span5">

            <input type="hidden" name="cdate" id="cdate" value="" />

            <div class="control-group">
            <label class="control-label">Company Name: <span style="color: red;">*</span></label>
                <div class="controls">
                    <input type="text" id="name" name="name" value=""/>
                </div>
            </div>  

            <div class="control-group">
            <label class="control-label">Company Abbreviation:<span style="color: red;">*</span></label>
                <div class="controls">
                    <input type="text" id="abbreviation" name="abbreviation" value=""/>
                </div>
            </div>      


            <div class="control-group">
            <label class="control-label">Company Image: </label>
                <div class="controls">
                        <input type="file" name="client_image" size="20" /> 
                </div>
            </div>

            </div>  

            <div class="span5">

            <div class="control-group">
            <label class="control-label">Website:</label>
                <div class="controls">
                    <input type="text" id="website" name="website" value=""/> 
                </div>
            </div>  

       </div>

    </div>  



<div class="row-fluid">
    <div class="span5" style="margin-top: 25px;">

    <div class="control-group">
            <div class="controls">
                <p><strong>Client</strong></p>
            </div>
    </div>  


    <div class="control-group">
        <label class="control-label">Address 1:</label>
            <div class="controls">
                <input type="text" id="address1" name="address1" value=""/>
            </div>
    </div>  

    <div class="control-group">
        <label class="control-label">Address 2:</label>
            <div class="controls">
                <input type="text" id="address2" name="address2" value=""/>
            </div>
    </div>      

    <div class="control-group">
        <label class="control-label">City:</label>
            <div class="controls">
                <input type="text" name="city" id="city"  value=""/>
            </div>
    </div>  


    <div class="control-group">
        <label class="control-label">State:</label>
            <div class="controls">
                <?= form_dropdown('state', usa_state_list(), set_value('state'), 'id=state');  ?>     
            </div>
    </div>  

    <div class="control-group">
        <label class="control-label">Zip:</label>
            <div class="controls">
                <input type="text" id="zip" name="zip" value=""/>
            </div>
    </div>  

    <div class="control-group">
        <label class="control-label">Country:</label>
            <div class="controls">
                <?= form_dropdown('country', country_list(), set_value('country'), 'id=country');  ?>    
            </div>
    </div>

  </div>
</div>
</div>

  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button type="submit" class="btn btn-primary" id="create_btn">Create Company</button>
  </div>
 </form> 
</div>

再说一遍,总结一下 . 使用input type =“button”,我的验证在模态中工作得很好,只有公司名称与company_id,user_id,active和cdate一起插入数据库 .

现在,使用input type =“submit”,所有数据插入都很棒,但验证失败并且无法找到重定向到页面的内容 .

再次,谢谢!

1 回答

  • 1

    问题在于你的ajax函数调用 .

    您需要阻止表单触发(从而通过post提交到操作中的url):

    更改:

    $('#create_btn').live('click', function(){
    

    至:

    $('#create_btn').live('click', function(e){
        e.preventDefault();
    

    should 解决了这个问题 . 如果它没有做更多的挖掘 . 我还建议将 live 切换到 on ,以便您自己将来证明自己 . on 在单个函数中处理与live,bind等相同的东西,效率更高 .

    编辑:为了解释发生了什么(以及为什么必须使用 e.preventDefault(); ),这是因为 <input type="submit"> 实际上会将表单提交到 <form> 标记的 action 属性中指定的URL . 因此,您的代码发生的事情是,只要您单击按钮,您的javascript就会立即运行,之后会立即发生本机浏览器提交事件 .

相关问题