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>



28 responses to "Blog | How to load dynamic content in a jQuery UI dialog via AJAX"

  1. daudi says at July 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 says at September 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 says at September 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 says at September 23, 2011 at 12:21 PM

    I am getting object does not support dialog method

  5. Hari says at September 23, 2011 at 12:24 PM

    Error: Object doesn't support property or method 'dialog'

  6. Hari says at September 23, 2011 at 1:26 PM

    Ignore my previous comments. it is working nw for me.
    thank you

  7. Manuelgc says at October 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 says at December 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 says at February 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 says at July 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 says at October 07, 2012 at 4:24 AM

    @Vikrant Thanks for the nice example.

    @Erik Thanks for the tip on the placeholder.

  12. Pia says at October 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 says at January 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 says at January 16, 2013 at 4:23 AM

    Also - Great tutorial, helped me out alot. Thanks! :)

  15. Affeveeldesse says at June 11, 2013 at 11:50 PM

    kvmfh <a href="http://chenelette.fr/xmlrpc/cache/monsterbeats.html">http://chenelette.fr/xmlrpc/cache/monsterbeats.html</a>gbvle <a href="http://www.clossaintjean.fr/components/com_mailto/casquebeatsbydre.html">http://www.clossaintjean.fr/components/com_mailto/casquebeatsbydre.html</a> vivxg <a href="http://www.bordelongue.com/gf5cfrc93ic/index_lv.html">Louis Vuitton</a> uctxe <a href="http://www.carrieres-gontero.com/Library/ceinturelouisvuitton.html">http://www.carrieres-gontero.com/Library/ceinturelouisvuitton.html</a> cmczg <a href="http://www.spheremedical.com/documents/video/cheapchristianlouboutinshoesuk.html">Christian Louboutin</a> we

  16. Bowalbula says at June 13, 2013 at 11:21 PM

    ckcvj <a href="http://velinabracelets.com/maps/bcpmylife.html">Louis Vuitton Handbags</a> qemjy <a href="http://www.wildsidewest.com/maps/cheapmlbjerseys.html">mlb Jerseys</a> qxvtm <a href="http://www.wildsidewest.com/maps/cheapnbajerseys.html">http://www.wildsidewest.com/maps/cheapnbajerseys.html</a> zgdtk <a href="http://www.the-tribes-foundation.org/images/mulberrybagssale26.html">Mulberry Sale</a> vzgvo <a href="http://www.walkingnyctours.com/images/custombeatsbydre05.html">Custom Beats By Dre</a> xl

  17. Sammiseerma says at June 15, 2013 at 2:20 AM

    <a href="http://www.uschapterwest.org/images/cheapnbajerseys4.html">http://www.uschapterwest.org/images/cheapnbajerseys4.html</a>

  18. Bowalbula says at June 16, 2013 at 7:47 AM

    qfnhh <a href="http://www.verterra.com/Uploads/discountlouisvuittonhandbags43.html">http://www.verterra.com/Uploads/discountlouisvuittonhandbags43.html</a> lcdmd <a href="http://www.yewjournal.com/images/cheapnhljerseys6.html">wholesale nhl jerseys</a> sqygv <a href="http://www.iiethai.org/web/download/cheapsoccerjerseys.html">Cheap soccer Jerseys</a> tgktu <a href="http://www.iiethai.org/web/download/cheapnfljerseys.html">nfl Jerseys</a> oxbns <a href="http://www.sodas.ch/html/chaneljapan.html">シャネル 財布</a> ni

  19. Sammiseerma says at June 17, 2013 at 4:11 AM

    <a href="http://www.uschapterwest.org/images/cheapnbajerseys4.html">wholesale nba jerseys</a>

  20. hoibioneedy says at June 17, 2013 at 3:33 PM

    tbmxl <a href="http://www.cedepe.fr/ug/nikepascher31.html">Nike Pas cher</a> hbnmh <a href="http://sanjuanrcd.org/blog/cheapsnapbackhats11.html">Cheap snapback hats</a> kgkna <a href="http://www.yewjournal.com/map/cheapsnapbackhats12.html">Cheap snapback hats</a> ixyct <a href="http://www.trudyebell.com/images/cheapsnapbacks09.html">http://www.trudyebell.com/images/cheapsnapbacks09.html</a> ewwvm <a href="http://www.itg4.com/CMSFiles/newerahats07.html">New Era Hats</a> gsjio

  21. Affeveeldesse says at June 17, 2013 at 6:16 PM

    fuv <a href="http://www.carecorner.ch/images/chanelbagsshop.html">chanel バッグ</a> ulv <a href="http://www.sodas.ch/html/chaneljapan.html">http://www.sodas.ch/html/chaneljapan.html</a> ixi <a href="http://www.oswa.ch/chaneljp.html">chanel バッグ</a> ydb <a href="http://www.iiethai.org/web/download/chanelonline.html">chanel 財布</a> lhh <a href="http://www.gienhistorie.dk/images/LouisVuittonjp.html">ルイヴィトン 財布</a> ybd

  22. Bowalbula says at June 18, 2013 at 4:35 PM

    vdmwp <a href="http://www.verterra.com/Uploads/discountlouisvuittonhandbags43.html">Louis Vuitton Outlet</a> msgmo <a href="http://www.yewjournal.com/images/cheapnhljerseys6.html">http://www.yewjournal.com/images/cheapnhljerseys6.html</a> hqtdg <a href="http://www.iiethai.org/web/download/cheapsoccerjerseys.html">Cheap Jerseys</a> mwclm <a href="http://www.iiethai.org/web/download/cheapnfljerseys.html">http://www.iiethai.org/web/download/cheapnfljerseys.html</a> jgtpd <a href="http://www.sodas.ch/html/chaneljapan.html">http://www.sodas.ch/html/chaneljapan.html</a> fp

  23. Affeveeldesse says at June 18, 2013 at 4:46 PM

    foe <a href="http://www.carecorner.ch/images/chanelbagsshop.html">http://www.carecorner.ch/images/chanelbagsshop.html</a> njl <a href="http://www.sodas.ch/html/chaneljapan.html">chanel 財布</a> pkr <a href="http://www.oswa.ch/chaneljp.html">chanel バッグ</a> iiq <a href="http://www.iiethai.org/web/download/chanelonline.html">chanel 財布</a> nqx <a href="http://www.gienhistorie.dk/images/LouisVuittonjp.html">ルイヴィトン 財布</a> gxq

  24. hoibioneedy says at June 18, 2013 at 6:49 PM

    bxkwc <a href="http://www.cedepe.fr/ug/nikepascher31.html">air max</a> uapuz <a href="http://sanjuanrcd.org/blog/cheapsnapbackhats11.html">Cheap snapback</a> iyjbp <a href="http://www.yewjournal.com/map/cheapsnapbackhats12.html">Cheap snapback hats</a> rljcj <a href="http://www.trudyebell.com/images/cheapsnapbacks09.html">snapbacks</a> ofafe <a href="http://www.itg4.com/CMSFiles/newerahats07.html">Cheap New Era Hats</a> ovbid

  25. Hinaoxicino says at June 19, 2013 at 2:24 PM

    ksgcv <a href="http://www.uschapterwest.org/images/cheapnbajerseys4.html">http://www.uschapterwest.org/images/cheapnbajerseys4.html</a> chofy <a href="http://www.sanjuanrcd.org/images/cheapauthenticjerseys8.html">cheap jerseys</a> bsfmi <a href="http://www.omnistech.com/CMSFiles/cheapoakleysunglasses14.html">Cheap oakley sunglasses</a> ycsvl <a href="http://eserv.biz/Classes/_vti_cnf/chanelbagsjp.html">シャネル</a> mukqr <a href="http://www.carecorner.ch/images/chanelbagsshop.html">http://www.carecorner.ch/images/chanelbagsshop.html</a> gt

  26. Sammiseerma says at June 19, 2013 at 4:27 PM

    <a href="http://www.uschapterwest.org/images/cheapnbajerseys4.html">cheap nba jerseys</a>

  27. Affeveeldesse says at June 19, 2013 at 8:45 PM

    jcv <a href="http://www.carecorner.ch/images/chanelbagsshop.html">http://www.carecorner.ch/images/chanelbagsshop.html</a> kbq <a href="http://www.sodas.ch/html/chaneljapan.html">chanel 財布</a> kiw <a href="http://www.oswa.ch/chaneljp.html">chanel バッグ</a> pfq <a href="http://www.iiethai.org/web/download/chanelonline.html">chanel 財布</a> uju <a href="http://www.gienhistorie.dk/images/LouisVuittonjp.html">ルイヴィトン バッグ</a> ken

  28. hoibioneedy says at June 20, 2013 at 3:34 AM

    rxkzr <a href="http://www.cedepe.fr/ug/nikepascher31.html">Nike Pas cher</a> fcgrm <a href="http://sanjuanrcd.org/blog/cheapsnapbackhats11.html">Cheap snapback hats</a> qxwtq <a href="http://www.yewjournal.com/map/cheapsnapbackhats12.html">Cheap snapback hats</a> goghp <a href="http://www.trudyebell.com/images/cheapsnapbacks09.html">snapbacks</a> snstt <a href="http://www.itg4.com/CMSFiles/newerahats07.html">http://www.itg4.com/CMSFiles/newerahats07.html</a> msqno



Post a comment


(lesstile enabled - surround code blocks with ---)

Featured posts

Subscribe to this blog

Blog topics