Search code examples
jqueryajaxfancybox

Fancybox success function close() is not working in ajax


index.php

 jQuery(function ($) {
      $("a.edit").fancybox();
 });


<a class="edit" href="showForm.php?id=<?=$row['id']?>"> Edit </a>

showForm.php

$id = $_GET['id'];

jQuery(function ($) {
$('#btnSend').click(function(){

        var key = $('input:hidden[name=id]').val();

        $.ajax({
                url: "process.php", 
                type: "POST",
                data: { "something": "something", "id": key}, 
                success: function(response) {
                    // I'm sure do something can work //

                    $.fancybox.close();  //this not work!
                    // parent.$.fancybox.close(); // or this
                }
        }); 
    });
});


<body>  
   *edit something...*

   <input type="hidden" name="id" value="<?=$id?>">
   <input type="button" id="btnSend" value=" Submit ">
</body>

process.php

$id = $_POST['id']; 
$something = $_POST['something'];

$sql = "UPDATE db 
        SET 
        something           =   '{$something}',
        WHERE id = '{$id}' ";
$result = $mysql->query($sql);  

I can update my data, but
$.fancybox.close();
jQuery.fancybox.close();
parent.$.fancybox.close();
all can't work...

version: fancybox-1.3.4

PS: when I use Ajax to submit form in samepage(index.php) , the $.fancybox.close(); can work!


Solution

  • I've posted unpacked version of jquery.fancybox-1.3.4.js: https://gist.github.com/vladkras/008361d790668634db74 to figure out what's happening.

    While your close() function fires, it seems to stop at line 926:

    if (busy || wrap.is(':hidden')) {
    

    where wrap = $('<div id="fancybox-wrap"></div>') is undefined according to you error. Try to put type: "iframe" to your fancybox options:

    $("a.edit").fancybox({
        type: "iframe"
    });
    

    to let it now, that it has parent

    UPD Also, are you sure you need that intermediate file showForm.php? It turns out that you make two ajax requests

    index.php ----------> showForm.php ------------> process.php
               fancybox                     ajax
    

    I think you can modify whole process:

    1. recieve element fom db with ajax
    2. create form with values on fly
    3. show your form with fancybox
    4. send changed data back
    5. $.fancybox.close() on success