отправить форму на тип fancybox iframe, возвращающий данные и сообщение от контроллера на родительскую страницу?

Я использую iframe типа fancybox и помещаю в него форму. У меня есть ссылка типа кнопки (не ввод кнопки отправки).
Я хочу, чтобы после отправки формы fancybox закрывался и возвращал поля формы и флеш-данные сообщения (в CodeIgniter) на родительскую страницу.
Код ниже:
РОДИТЕЛЬСКАЯ СТРАНИЦА
//click button from parent page, popup fancybox form (type iframe)

<a class="addnew hand-pointer" data-height="410" onclick="addnew();">Add new user</a>
<script type="text/javascript">
function addnew() {
    var url = '<?php echo $base_url; ?>' + 'ctl_user/load_popup_add_user';
    CreateFancyBox('a.addnew', url, '45%', 390);
}
<script>

СТРАНИЦА ИНФРАММА:

<div style="background-color: white;">
    <form id="frmAddUser" method="post" action="">
        <table id="tblUserAdd" cellpadding="0" cellspacing="10" width="100%" border="0">
......
<tr>
<td></td>
      <td class="t-right">
      <a id="btnAdd" class="apply hand-pointer">Apply</a>
      <a href="#" class="cancel">Cancel</a>
      </td>
</tr>
</table>
        <input type="hidden" name="add" value="add_new_user" />
    </form>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $('#btnAdd').click(function(e)
        {
            e.preventDefault();
            $('#frmAddUser').bind('submit', function() 
            {
                $.ajax({
                    type: 'POST',
                    url: '<?php echo $base_url; ?>ctl_user/add_user',
                    data: $(this).serializeArray(),
                    success: function(data) {
                        //close fancybox
                        parent.$.fancybox.close();
                        //return data form fields to parent page
                                                //I dont know to write any more
                    }
                });
            });
        });
    });
</script>

КОД СОЗДАЙТЕ FANCYBOX:

function CreateFancyBox(selector, url, width, height) {
    $(selector).fancybox({
        'href': url,
        'scrolling'         : 'no',
        'titleShow'         : false,
        'titlePosition'     : 'none',
        'openEffect'        : 'elastic',
        'closeEffect'       : 'none',
        'closeClick'        : false,
        'openSpeed'         : 'fast',
        'type'              : 'iframe',
        'padding'           : 0,
        'preload'           : true,
        'width'             : width,
        'height'            : height,
        'fitToView'         : false,
        'autoSize'          : false,
        'helpers'           : { 
            overlay :   {
                'closeClick': false,
            }
        },
        afterClose          : function() { //I search StackOverflow, add this function to reload parent page, it will appear the flash data message notification which I write on controller "add_user"
            parent.location.reload();
        }
    });
}

Код CONTROLLER в CODEIGNITER, используемый для добавления пользователя в базу данных:

public function add_user() {
        // var_dump('hehehe');
        $departmentid    = $this->input->post('department');
        $fname           = $this->input->post('fullname');
        $email           = $this->input->post('email');
        $mobile          = $this->input->post('mobile');
        $result = $this->user->add_new_user($departmentid, $fname, $email, $mobile);
        if($result != FALSE) {
            $this->session->set_flashdata('msg','Success! New user has been added!');
            $this->session->set_flashdata('type_msg','success');
        } else {
            $this->session->set_flashdata('msg','Error! Can\'t add user!');
            $this->session->set_flashdata('type_msg','error');
        }
        if($this->input->post('add_new_user')) {
            header('Location: '.base_url().'ctl_user'); //return parent page after add user to database and close popup fancybox
            exit;
        }
    }

Но я не закрываю этот fancybox, и данные не отправляются в мою базу данных, и я не получаю уведомление о сообщении с родительской страницы.

Я использую последнюю версию fancybox (2.0).

Подскажите как решить эту проблему! :(


person amidamaru    schedule 12.07.2013    source источник


Ответы (2)


Вы немного перепутали привязки событий. Вы привязываетесь к событию, когда событие запускается.

Пытаться

$(document).ready(function() {
   $('#frmAddUser').bind('submit', function() 
        {
            $.ajax({
                type: 'POST',
                url: '<?php echo $base_url; ?>ctl_user/add_user',
                data: $(this).serializeArray(),
                success: function(data) {
                    //close fancybox
                    parent.$.fancybox.close();
                    //return data form fields to parent page
                                            //I dont know to write any more
                }
            });
        });
    $('#btnAdd').click(function(e)
    {
        $('#frmAddUser').trigger('submit');
        e.preventDefault();

    });
});
person Casey Flynn    schedule 12.07.2013

Я бы предложил другую технику. Просто отправьте форму обычно методу контроллера и вставьте данные в базу данных в зависимости от ваших условий, которые вы можете написать:

echo '<script type="text/javascript">parent.$.fancybox.close();</script>';
redirect('controller/method', 'refresh');
person Nil'z    schedule 12.07.2013
comment
не могли бы вы показать мне подробно, как вы это сделали? Если у вас есть демо, я хотел бы знать, как у вас дела. - person amidamaru; 13.07.2013