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>

38 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. 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). http://Groupescac.com/?option=com_k2&view=itemlist&task=user&id=1038067
  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. http://www.fabioturin.it/?option=com_k2&view=itemlist&task=user&id=919638
  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. http://gestionatuproyecto.es/?option=com_k2&view=itemlist&task=user&id=233049
  24. Rogelio
    Rogelio Nov 27, 2016 at 1:47 PM
    Esto nos pasa tanto con regalos para hombres como con regalos para mujeres. http://9dimen.com/comment/html/index.php?page=1&id=8162
  25. Barbara
    Barbara Dec 07, 2016 at 4:55 AM
    ESIC dispone de un programa propio de ayudas económicas de diferentes tipos. http://sahakorn.pmk.ac.th/?option=com_k2&view=itemlist&task=user&id=486925
  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. http://greenblood.s12.xrea.com/cgi-bin/hamima2/yuu-fantasy.cgi
  29. salon de massage lyon
    salon de massage lyon Apr 13, 2017 at 4:18 PM
    http://www.sophiechassat.com
  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
    http://your-tv-online.blogspot.com/
    http://foros.vogue.es/viewtopic.php?f=60&t=228866
    http://forum.vbulletin-germany.com/member.php/69684-soniacastellano
    http://captainamericalesoldatdelhiver.blogspot.com/
  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
    http://armorgames.com/user/codigopromocional
    http://forum.html.it/forum/member.php?userid=432432
    https://eu.portal.sf.my.com/comments/5926bd5aac72748b1578e16e
    http://it.toolbox.com/people/codigopromocional/
  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
    http://www.expansion.com/social/usuarios/codigopromocional/
    https://www.motorpasion.com/usuario/soniacastellanos
    https://esports.xataka.com/usuario/soniacastellanos
    https://allods.my.com/forum/index.php?page=UserGuestbook&userID=69839&entryID=872
  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
  35. chaturbate token hack youtube
    chaturbate token hack youtube Aug 28, 2017 at 1:27 PM
    Right here is the perfect site for anybody who wants to understand this topic.
    You know so much its almost tough to argue with you (not that I actually will need to…HaHa).

    You definitely put a brand new spin on a topic that's been written about for ages.
    Excellent stuff, just wonderful! http://chaturbatetokenshack.online/
  36. Heriberto
    Heriberto Sep 05, 2017 at 1:17 AM
    Could there be a little something known as cat mario unblocked?
    Evidently, loads of sites never deliver totally
    free capability to customers to relax and play the video
    game. Inside the feeling, the sport is just not fully available on the internet and infrequently, indeed very rarely you can find some websites delivering and totally
    free and complete accessibility online game. Moreover, if you find an individual or any, please
    do let us. We now have been looking for some cat mario unblocked request.
    Anyways, moving on to a different component
    about Cat Mario, we have to be frank on this
    page again and say that free game download of subway surfers (http://www.cnc-engravers.ru/user/subwaysurfershackapk) no get older confines.

    You can perform this game as well as main purpose
    than it is usually to have fun with this whenever possible but while there is nothing at all called as cat mario unblocked, plenty
    of your satisfaction removal will hinge after that you participate in this game.
    The official site is the place you can give it a try but there may be some
    repayment to become designed.

    Hi there! This is amongst the most effective activity from Weebly
    and it's totally unblocked! Play Cat Mario in class, perform or in the home daily.
    Have a great time!

    Cat Mario 2 , 3 Match Unblocked Syobon Activity can be a two
    dimensional Japanese program freeware indie video game unveiled in February 2007.

    This step match provides a unique handle one of many world’s most desired gaming
    systems. Lead the bright feline throughout the Mushroom Kingdom.
    In lieu of Goombas and Koopas, you will be facing an army of
    icky blobs.

    Help a little bit Cat Mario overcome all issues! In this particular unblocked game for college, you have to
    manage your kitty and then make its way by means
    of all discrepant destinations filled up with impediments.

    Work through them all, gather far more helpful merchandise and attempt your better to defeat all adversaries.
    All the best!
  37. Tilly
    Tilly Sep 06, 2017 at 7:17 PM
    Hello very nice blog!! Guy .. Beautiful .. Superb .. I'll bookmark your website and take the feeds
    additionally? I'm satisfied to find numerous useful information here
    within the submit, we'd like work out more strategies in this regard, thanks for sharing.
    . . . . . http://www.zoneti.ca/?option=com_k2&view=itemlist&task=user&id=1343831
  38. real psychic
    real psychic Oct 09, 2017 at 8:54 PM

    Wonderful work! That is the type of information that
    should be shared around the web. Shame on the seek engines for not positioning this post higher!

    Come on over and seek advice from my website . Thank you =)
    http://realpsychicnow.biz

Post a comment