views:

258

answers:

2

I have a dialog box that has AJAX loaded content.

I want to have two buttons on the dialog box: a next and previous, which will load new AJAX content into the dialog box.

Is it better to re-use the current dialog box, or destroy it and create a new one?

When I've tried re-using the dialog boxes (by updating an internal div with fresh AJAX content), the dialog box doesn't want to display it.

When I've tried destroying and creating a new one, it will often show two dialog boxes (the new and the old).

Any ideas?

A: 

The dialog can be tricky to understand how to reuse it.

Try something like this:

var cur = 1;
$("#dialog").load('ajax/content'+cur+'.html').dialog({
    buttons: {
     Next: function() {
      cur++;
      $(this).load('ajax/content'+cur+'.html');
     },
     Previous: function() {
      cur--;
      $(this).load('ajax/content'+cur+'.html');
     }
    }
});

Should help you get what you want.

PetersenDidIt
A: 

Thanks petersendidit. I used a similar sort of idea, but I had to rework it for my dynamic php and AJAX powered site.

The key to getting it to work was creating a div on the fly, rather than using an existing one in the DOM. When the user clicks next or previous, the dialog box is destroyed and a new one is dynamically created again.

In the example below, I needed a dialog box to page through different students. The students_ids variable are passed from php as a string. eg. stuid1|stuid2|stuid3. The current_student is one of those ids. eg. stuid2.

function opendialog_student(url, title, current_student, students_ids) {
var $dialog = $('<div></div>');
$dialog.load(url + '&student_id=' + current_student);
$dialog.dialog({ title: title, modal: true, draggable: false, resizable: false, closeOnEscape: false, position: 'top', width: 800, height: 600,
    buttons: { "Next Student": function() { 
        students = students_ids.split('|');
        for (var i = 0;i<students.length;i++) {
            if (students[i] == current_student) {
                var next_student = students[i+1];
            }
        }
        if (!next_student) {
            next_student = students[0];
        }
        opendialog_student(url, title, next_student, students_ids);
        $dialog.dialog('destroy');
    }, "Previous Student": function() { 
        students = students_ids.split('|');
        for (var i = 0;i<students.length;i++) {
            if (students[i] == current_student) {
                var previous_student = students[0];
            }
        }
        if (!previous_student) {
            previous_student = students[0];
        }
        opendialog_student(url, title, previous_student, students_ids);
        $dialog.dialog('destroy');
    } },
    close: function() { 
        $dialog.dialog('destroy');
    }
});

}

Paul