使用JQuery Ajax和Modal Bootstrap发布到CI控制器

时间:2013-05-27 22:24:51

标签: javascript jquery ajax codeigniter

我正在使用Bootstrap Modal获取用户的输入并将其提交给CI控制器进行验证。我希望能够在将输入保存到数据库表之前将结果返回到相同的模态(JSON)。从代码到目前为止,Firebug告诉我我有一个TypeError:结果为null。我想让它发挥作用。我是JQuery / Ajax的新手。感谢您的帮助。

脚本

$(document).ready(function() {

$('#createCardId').click('click', function(e) {
    e.preventDefault();
    //we'll want to move to page specific files later

    var email = $('input#email').val(); //from hidden field
    var location = $('input#location').val(); //from hidden field
    var card = $('#cardId').val(); //user's input

    $.ajax({
        url : "../edituser/addCardId",
        dataType : "json",
        type : 'POST',
        data : "email=" + email + "&location=" + location + "&CardId=" + card,
        success : function(result) {

            if (result.error) {
                $(".alert").fadeIn('slow');
                $("#error_message").html(result.message);

            } else {

                $(".alert").fadeIn('slow');
                $("#error_message").html(result.message);
                $('#new_item').modal('hide');
            }

        },
    });

});

});         

View-Modal Bootstrap

        <div id="myModal" class="modal hide fade modal-admin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Add Card ID</h3>
      </div>
      <div class="modal-body">
        <!--############-->
        <!-- column left -->
        <div class="span6">
        <p>
            <?php 

            $location = $this->session->userdata('location');
            $email = $account->email;
            echo $location. '<br>'; 
            echo $email;


            if(validation_errors())
            {
                echo '<div class="alert alert-error">'.validation_errors().'</div>';
            }
            ?>


        <!--CARD ID -->
        <div id="error_message"></div> 
        <div class="control-group">
        <input id="email" type="hidden" name="email" value="<?php echo $email; ?>">
        <input id="location" type="hidden" name="location" value="<?php echo $location; ?>">    
        <label class="control-label">Card ID: <span style="color: red;">*</span></label>
            <div class="controls">
                <input type="text" id="cardId" name="cardId" value=""/>
            </div>
        </div> 
        <!--END OF CARD ID-->
        </p>
        </div>
        <!--############ column left ends-->

        <!--############-->
        <!--column right-->

        <div class="span6">
            <p>Hello <?php echo $location; ?></p>
        </div>
        <!--############ column right ends-->
      </div>
      <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
        <button class="btn btn-primary" id="createCardId" "data-dismiss=modal">Save changes</button>
        <!--<input name="submit" type="submit" id="submit" value="Save Changes" class="btn btn-primary">-->

      </div>


      <!--############-->



    </div>    

CI控制器

public function addCardId()
{

    $this->form_validation->set_rules('CardId', 'Card Id', 'required|trim|xss_clean|max_length[6]|is_unique[accounts.CardId]');
    $email = $this->input->post('email');
    $location = $this->input->post('location');
     $result = array();

     if ($this->input->is_ajax_request()) 
    {

        if ($this->form_validation->run() == FALSE) {
            $result['error'] = true;
            $result['message'] = validation_errors();

         } else {

            $result['error'] = TRUE;
            $result['message'] = 'The Card ID has been saved';           

            //Model will load here to add Card ID to the database.               
            redirect('admin/editaccount/search_account', 'refresh');
        }  


        $json = json_encode($result);
        die($json);
    }
    else
    {

        redirect('../searchaccount/showresults', 'refresh');
    }

}

感谢您的帮助!!

2 个答案:

答案 0 :(得分:0)

检查你的控制器:

if ($this->input->is_ajax_request()) 
{
    if ($this->form_validation->run() == FALSE) {
        $result['error'] = true;
        $result['message'] = validation_errors();

     } else {
        $result['error'] = FALSE; //TRUE; should be FALSE
        $result['message'] = 'The Card ID has been saved';           

        // Model will load here to add Card ID to the database.
        // Why redirect this AJAX request?
        // redirect('admin/editaccount/search_account', 'refresh');
    }  

    $json = json_encode($result);
    die($json);
}

尝试将result值输出到控制台:

$.ajax({
    ...
    success : function(result) {
        // Add this line
        console.log(result);
        if (result.error) {
            $(".alert").fadeIn('slow');
            $("#error_message").html(result.message);

        } else {
            $(".alert").fadeIn('slow');
            $("#error_message").html(result.message);
            $('#new_item').modal('hide');
        }

    },
});

答案 1 :(得分:0)

我终于完成了我需要的东西。这是代码。

查看

<!-- model content -->    
<div id="form-content" class="modal hide fade in" style="display: none; ">
        <div class="modal-header">
              <a class="close" data-dismiss="modal">×</a>
              <h3>Card ID</h3>
        </div>
    <div>
        <form class="contact">

             <div class="modal-body">
                 <ul class="nav nav-list">
           <input id="email" type="hidden" name="email" value="<?php echo $email; ?>">
           <input id="location" type="hidden" name="location" value="<?php echo $location; ?>">
           <label>Please enter a valid Card ID:</label>
           <input id="CardId" type="input" name="CardId"  maxlength="6"/>                
           </ul> 

            </div>

        </form>
    </div>
     <div class="modal-footer">
         <a href="#" class="btn" data-dismiss="modal">Close</a>
         <button class="btn btn-success" id="submit">Save Changes</button>
      </div>
</div>  
<?php
                if ($account -> CardId) {
                    echo $account -> CardId;
                } else {

                    echo "<div id='thanks'><p><a data-toggle='modal' href='#form-content' class='label label-addvisit'>Card ID</a></p></div>";
                }
                ?>  

<强>脚本

$(function() {

$("button#submit").click(function(){
        $.ajax({
        type: "POST",
    url: "../edituser/addCardId",
    data: $('form.contact').serialize(),
        success: function(msg){
                 $("#thanks").html(msg)
                $("#form-content").modal('hide');    
             },
    error: function(){
        alert("failure");
        }
          });
});

});

<强>控制器

public function addCardId()
{

     if ($this->input->is_ajax_request()) 
    {
                $email = $this->input->post('email');
        $location = $this->input->post('location');
        $CardId = $this->input->post('CardId');

        echo "<span class=\"label label-info\" >Card Id Assigned</span>";
    }


}    

我剩下要做的就是在控制器中运行一些验证。