The future is here. It's just not widely distributed yet. - William Gibson

How to load dynamic content in a jQuery UI dialog via AJAX

jQuery UI dialog allows you to display any content in a popup box, given the content is already present somewhere within page (e.g., in the DOM tree). However, you may want to display content in a popup box that has to be fetched from the server.

Now, here is how you can display a URL into a modal window (in-page popup) with jQuery UI dialog. Do note that this only works for pages hosted on the same domain because of same origin policy

The plain vanilla version


  function showUrlInDialog(url){
    var tag = $("<div></div>");
    $.ajax({
      url: url,
      success: function(data) {
        tag.html(data).dialog({modal: true}).dialog('open');
      }
    });
  }

And here’s how to use it


  <a href="#" onclick="showUrlInDialog('/feedback-form'); return false;">Give us feedback</a>

The extended version

Now, we’ll extend our example and add support for configurations, callbacks and other fancy stuff. First, we will add support for JSON response along with HTML. So, if the response from server is in HTML, we simply display it within the dialog box, and if the response is in JSON, we then assume that the JSON is in {"title": "...", "html": "..."} format, from which we use title to display the title of the dialog box and html to display the body of the dialog box. We’ll also add support for options like jQuery.ajax callbacks and some jQuery UI dialog options. You can of course extend the list to add your own callbacks and options. Here is the list of available options:

Following options are delegated to the Ajax call, see http://api.jquery.com/jQuery.ajax/ for documentation regarding these options.

1. type
2. beforeSend
3. error
4. complete

Some jQuery UI dialog options are also available in this example, see http://jqueryui.com/demos/dialog/ for more information.

1. modal
2. title


  function showUrlInDialog(url, options){
    options = options || {};
    var tag = $("<div></div>"); //This tag will the hold the dialog content.
    $.ajax({
      url: url,
      type: (options.type || 'GET'),
      beforeSend: options.beforeSend,
      error: options.error,
      complete: options.complete,
      success: function(data, textStatus, jqXHR) {
        if(typeof data == "object" && data.html) { //response is assumed to be JSON
          tag.html(data.html).dialog({modal: options.modal, title: data.title}).dialog('open');
        } else { //response is assumed to be HTML
          tag.html(data).dialog({modal: options.modal, title: options.title}).dialog('open');
        }
        $.isFunction(options.success) && (options.success)(data, textStatus, jqXHR);
      }
    });
  }

Again, you can use it like:


  <a href="#" onclick="showUrlInDialog('/feedback-form', {error: function() { alert('Could not load form') }}); return false;">Give us feedback</a>

22 Comments Added

Join Discussion
  1. daudi
    daudi Jul 30, 2011 at 9:56 AM
    Thank you! This is the best jquery ui dialog example I've seen. Most are overly trivial. Very useful!
  2. question about the example
    question about the example Sep 10, 2011 at 1:06 AM
    Thanks for the code to display html in a dialogbox.

    However, when I use the example as it, it opens 2 dialogboxes. the first modal box is empty. the 2nd box has the content. This is problem #1.

    Problem #2: how do I use the dialog box options? Can you provide an example. You're second example doesn't appear to use the dialog box titles and modal option.

    I'm new to this and it would be helpful to expand your 2nd example.


    Thanks much!
  3. marlo
    marlo Sep 10, 2011 at 1:18 AM
    please disregard my comment. I figured out that the problem was other code. thanks for the "how-to"
  4. Hari
    Hari Sep 23, 2011 at 12:21 PM
    I am getting object does not support dialog method
  5. Hari
    Hari Sep 23, 2011 at 12:24 PM
    Error: Object doesn't support property or method 'dialog'
  6. Hari
    Hari Sep 23, 2011 at 1:26 PM
    Ignore my previous comments. it is working nw for me.
    thank you
  7. Manuelgc
    Manuelgc Oct 04, 2011 at 10:04 AM
    Hi, this example work fine for me, this is my code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    
    $('img.mas-info-pedido').live('click',function(e){                        
                            e.preventDefault();
                            var id_pedido = $(this).attr('alt');
                            var popup = $('#popup');
    
                            $.get('<?php echo base_url()?>index.php/usuario/c_datos_usuario/getPedidoPorId/'+id_pedido,                                                                                
                                            function(data){
                                                    /*var salida = '<table id="datos-pedido-usuario">';
                                                    salida += '<tr>'+data.direccion_envio_ciudad+'</tr>';
                                                    salida += '</table>';*/                                                
                                                    var salida = '';
                                                    salida += '<p> Fecha del pedido: '+data.fecha_pedido+' '+data.hora_pedido+'</p>';
                                                    salida += '<p> Cantidad total del pedido: '+data.cantidad+'</p>';
                                                    salida += '<p> Estado del pedido: '+data.estado_pedido+'</p>';
                                                    salida += '<p> Restaurante: '+data.tienda_comida+'</p>';
                                                    salida += '<p> Tipo de venta: '+data.tipo_venta+'</p>';
                                                    salida += '<p> Ciudad: '+data.direccion_envio_ciudad+'</p>';
                                                    salida += '<p> Zona: '+data.direccion_envio_zona+'</p>';
                                                    salida += '<p> Calle/Carrera: '+data.direccion_envio_calle+'</p>';
                                                    salida += '<p> Casa/Urb: '+data.direccion_envio_casa+'</p>';
                                                    salida += '<p> Lugar de referencia: '+data.direccion_envio_lugarref+'</p>';
                                                    salida += '<p> Subtotal: '+data.subtotal+'</p>';
                                                    salida += '<p> Iva: '+data.iva+'</p>';
                                                    salida += '<p> Total: '+data.total+'</p>';
    
                                                    popup.html(salida).dialog({
                                                            width:600,
                                                            title:'Pedido',
                                                            height: 500,
                                                            modal:true,
                                                            show:"blind",
                                                            hide:"explode"
                                                    }).dialog('open');                                                                                
                                    },
                                    'json'
                            );                                        
                    });
    
    Thanks for your help
  8. Dez
    Dez Dec 10, 2011 at 8:48 AM
    Thanks for this great tutorial. I was wondering if you could provide an example if I wanted to open a specific div #myanchor in the dialog instead of the entire page?
  9. Scott Mugford
    Scott Mugford Feb 26, 2012 at 8:13 AM
    if anyone can help me with this that would be awesome

    'http://stackoverflow.com/questions/9450046/unload-ajax-when-just-closing-a-jquery-ui-dialog'
  10. Erik Bongers
    Erik Bongers Jul 17, 2012 at 3:52 AM
    Hi, a small correction may be needed. Everytime you open a dialogbox, a new placeholder DIV is created. This means that the previous placeholder, containing the previous dialogbox, is still in the dom. This can lead to duplicate id's and other conflicts. My suggested correction is to reuse the placeholder DIV:
    1
    2
    3
    4
    
    //This tag will the hold the dialog content.
        var tag = $("#dialogHolder");
        if(!tag.length)
            tag = $("<div id='dialogHolder'></div>"); 
    

    I noticed this error when my some function in my dialogbox only worked the first time I called it.
    Haven't tested yet what happens if dialog1 opens dialog2 though...cleanup of old dialogs may prove to be a bit more complex in that case.
  11. atmchuck
    atmchuck Oct 07, 2012 at 4:24 AM
    @Vikrant Thanks for the nice example.

    @Erik Thanks for the tip on the placeholder.
  12. Pia
    Pia Oct 13, 2012 at 7:58 PM
    I tried this out however when it returns a 'Could not load form' dialogue box. Why might this be happening?
  13. Garry
    Garry Jan 16, 2013 at 4:22 AM
    @pia - It sounds like your page (url) you're calling is having issues loading. Try to browse to that page separately first and see if your ajax page is working properly. Thats what happened to me.
  14. Garry
    Garry Jan 16, 2013 at 4:23 AM
    Also - Great tutorial, helped me out alot. Thanks! :)
  15. arpit jain
    arpit jain Jul 20, 2013 at 5:34 PM
    which jquery file should i call in this?
    <script src="http://code.jquery.com?????
  16. maani
    maani Nov 18, 2013 at 3:39 PM
    i couldnt get the title
  17. mani
    mani Nov 18, 2013 at 5:49 PM
    first time it executes but not in the second times
  18. hemavathy
    hemavathy Apr 16, 2014 at 4:07 PM
    hi,actually i have created event calendar using php,javascript,ajax json.i want to display my event's details in pop up window when i am clicking that particular event in the table.pls give correct code for that.
  19. gmade
    gmade May 13, 2014 at 8:42 PM
    How could this be modified to show a loading spinner while the dialog loads up?
  20. Yair
    Yair May 16, 2014 at 12:48 AM
    Excellent answer thanks =)
  21. veerakumar.A
    veerakumar.A Aug 07, 2014 at 5:41 PM
    Thanks for your valuable posting, it was very informative. Am working in < a href="http://www.excelanto.com"> CMS In Chennai </a>.
  22. veerakumar.A
    veerakumar.A Aug 07, 2014 at 5:41 PM
    Thanks for your valuable posting, it was very informative. Am working in < a href="http://www.excelanto.com"> CMS In Chennai </a>.

Post a comment