【问题标题】:AJAX within a modal inserting a form in CodeIgniter在 CodeIgniter 中插入表单的模式中的 AJAX
【发布时间】:2012-10-06 19:42:17
【问题描述】:

为此苦苦挣扎了大约 4 个小时,我试图创建一个模式下拉菜单(Twitter 引导模式),其中包含创建公司的表单。这是在 CodeIgniter 中构建的。

我在输入 type="submit" 和 input type="button" 方面遇到问题。

我只有 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",所有数据都可以很好地插入,但是验证失败,并且找不到重定向到页面。

再次感谢!

【问题讨论】:

    标签: ajax codeigniter modal-dialog


    【解决方案1】:

    问题在于您的 ajax 函数调用。

    您需要阻止表单触发(从而通过帖子提交到正在运行的 url):

    变化:

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

    收件人:

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

    应该解决问题。如果没有,请告诉我,我会做更多的挖掘工作。我还建议将live 切换为on,这样您就可以适应未来。 on 在单个函数中处理与 live、bind 等相同的内容,效率更高。

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

    【讨论】:

    • 很好,这确实修复了验证。但是,我仍然无法将所有其他输入字段插入数据库...
    • 另外,我的重定向不起作用。当我单击“创建公司”时,它什么也不做,并保持模式打开。它将公司名称与其他 ID 和 cdate 一起存储在数据库中。我不明白为什么要插入名称而不是其他字段。我已经尝试将其他字段添加到验证中
    • 首先,您应该将$_POST 引用为$this-&gt;input-&gt;post()。然后,为了调试,首先尝试将if($_POST) 块更改为die(var_dump($this-&gt;input-&gt;post()));。然后alert() ajax 调用内的complete: 事件中的响应对象。这将告诉您实际发送到脚本的内容。
    • 嗯,设置有问题,不过我会得到它。感谢您的帮助,我们会给予代表!
    • 我鼓励你只是投票而不是标记正确......其他人可能对此有更多见解。稍后我可能会提供更具体的调试示例。但是,您应该从简单开始,然后增加复杂性,以便您知道什么时候出了问题。
    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2011-06-03
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多