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>");
      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 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 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.
      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>

34 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:
                            var id_pedido = $(this).attr('alt');
                            var popup = $('#popup');
                            $.get('<?php echo base_url()?>index.php/usuario/c_datos_usuario/getPedidoPorId/'+id_pedido,                                                                                
                                                    /*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: ''</p>';
                                                            height: 500,
    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

  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:
    //This tag will the hold the dialog content.
        var tag = $("#dialogHolder");
            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="
  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. Brock
    Brock Nov 19, 2016 at 10:41 PM
    Realizamos tanto la limpieza puntual como el mantenimiento periódico de todo
    género de garajes, utilizando siempre y en todo
    momento la más moderna maquinaria (aspiradoras industriales, máquinas barredoras y fregadoras,
    máquinas hidrolimpiadoras según la superficie).
  22. Margaret
    Margaret Nov 21, 2016 at 6:00 AM
    Intersticial: Formato promocional que aparece ocupando la pantalla
    completa durante unos segundos antes de visualizar el contenido de una web.
  23. socorrista madrid empleo 2015
    socorrista madrid empleo 2015 Nov 22, 2016 at 7:24 PM
    Ofrecemos servicios de mantenimiento de piscinas de gran calidad a un costo que no tienen ninguna competencia en toda la Comunidad de la
    capital de España.
  24. Rogelio
    Rogelio Nov 27, 2016 at 1:47 PM
    Esto nos pasa tanto con regalos para hombres como con regalos para mujeres.
  25. Barbara
    Barbara Dec 07, 2016 at 4:55 AM
    ESIC dispone de un programa propio de ayudas económicas de diferentes tipos.
  26. Verona
    Verona Dec 24, 2016 at 8:07 AM
    виза в америку для неработающих
  27. Owen
    Owen Jan 16, 2017 at 7:49 PM
    Ebay same style cheap authentic jersey to offer. Online free shipping - European Championship
  28. Maria Catarina
    Maria Catarina Apr 11, 2017 at 9:31 AM
    Continue fortalecendo a imunidade de seu fruto com uma boa sustento
    para diminuir a ansa de ele se reinfectar no horizonte.
  29. salon de massage lyon
    salon de massage lyon Apr 13, 2017 at 4:18 PM
  30. Kali
    Kali Jul 01, 2017 at 1:29 PM
    Incredible! This blog looks exactly like my old one!
    It's on a completely different subject but it has pretty much the same page layout
    and design. Great choice of colors!
    webs de ofertas
  31. Anitra
    Anitra Jul 02, 2017 at 8:24 PM
    This post will help the internet people for creating new website or
    even a weblog from start to end.
    paginas de ofertas
  32. Shannon
    Shannon Jul 05, 2017 at 1:48 AM
    I love what you guys are up too. Such clever work and exposure!
    Keep up the awesome works guys I've you guys to blogroll.

    paginas con descuentos
  33. Samara
    Samara Jul 26, 2017 at 1:27 AM
    I am wholesale jerseys real supplier online, take coupon code here:
    wholesale jerseys authentic
  34. Joy
    Joy Aug 10, 2017 at 8:12 PM
    is it legal to order cialis online
    cialis generika
    order cialis daily

Post a comment